Python讀書筆記008:面向物件程式設計
阿新 • • 發佈:2019-02-07
編寫類:
class Person:
'''
Class to represent a person
'''
def __init__(self):
self.name = ''
self.age = 0
>>> p=Person() >>> p <__main__.Person object at 0x030D9CD0> >>> p.age 0 >>> p.name '' >>> p.age=55 >>> p.age 55 >>> p.name='Moe' >>> p.name 'Moe'
上述程式碼定義了一個名為Person的類。它定義了Person物件包含的資料和函式。它包含資料name和age,其中唯一的一個函式是__init__,這是用於初始化物件值的標準函式。所有類都應有方法__init__(self),這個方法的職責是初始化物件,如初始化物件的變數。self是一個指向物件本身的變數。
顯示物件
方法是在類中定義的函式。
class Person: ''' Class to represent a person ''' def __init__(self): self.name = '' self.age = 0 def display(self): print("Person('%s,%d')" % (self.name, self.age))
>>> p=Person()
>>> p.display()
Person('',0)
>>> p.name='Bob'
>>> p.age=25
>>> p.display()
Person('Bob',25)
特殊方法__str__用於生成物件的字串表示:
class Person: ''' Class to represent a person ''' def __init__(self): self.name = '' self.age = 0 def display(self): print("Person('%s',%d)" % (self.name, self.age)) def __str__(self): return "Person('%s',%d)" % (self.name, self.age)
>>> p=Person()
>>> str(p)
"Person('',0)"
str簡化display:
class Person:
'''
Class to represent a person
'''
def __init__(self):
self.name = ''
self.age = 0
def display(self):
print(str(self))
def __str__(self):
return "Person('%s',%d)" % (self.name, self.age)
>>> p=Person()
>>> p.display()
Person('',0)
>>> p.name='Bob'
>>> p.age=25
>>> p.display()
Person('Bob',25)
特殊方法__repr__:
class Person:
'''
Class to represent a person
'''
def __init__(self):
self.name = ''
self.age = 0
def display(self):
print(str(self))
def __str__(self):
return "Person('%s',%d)" % (self.name, self.age)
def __repr__(self):
return str(self)
>>> p=Person()
>>> p
Person('',0)
>>> str(p)
"Person('',0)"