python之類實例屬性

情況一:
class A:
def init(self):
pass
def setname(self,who):
self.name=who
object_a=A()
print(object_a.name)
此時會報錯, ‘A’ object has no attribute ‘name’,類對象A沒有屬性“name”
情況二:
class A:
def init(self):
pass
def setname(self,who):
self.name=who
object_a=A()
object_a=A()
object_a.setname(“bob”)
print(object_a.name)
當調用setname方法時,類A會把屬性“name”附加到實例之上
情況三:
class A:
def init(self):
self.name=“abc”
def setname(self,who):
self.name=who
object_a=A()
print(object_a.name)
此時不報錯,因爲 object_a=A()語句會調用__init__()函數
還可以通過這種方式添加實例屬性:
object_a=A()
object_a.age=25
print(object_a.age)
注意:
object_a=A()
object_a.__age=25
print(object_a.__age)
通過這種方式添加的__age屬性並不是私有屬性
python爲類實例添加屬性的方法與C++很不同

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章