類的屬性我們來看下一個類的申明,如下:
class Foo():
"""this is test class"""
def __init__(self, name):
self.name = name
def run(self):
print('running')
# 列出類的所有成員和屬性
dir(Foo)
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'run']
# 類的注釋
Foo.__doc__
# 'this is test class'
# 類自定義屬性
Foo.__dict__
mappingproxy({'__module__': '__main__',
'__doc__': 'this is test class',
'__init__': <function __main__.Foo.__init__(self, name)>,
'run': <function __main__.Foo.run(self)>,
'__dict__': <attribute '__dict__' of 'Foo' objects>,
'__weakref__': <attribute '__weakref__' of 'Foo' objects>})
# 類的父類
Foo.__base__
# 類的名字
Foo.__name__
類的實例化和初始化
# python類先通過__new__實例化,再調用__init__進行初始化類成員
foo = Foo('milk')
類的屬性添加和訪問
# 類的訪問
foo.name
foo.run()
# 可以通過setattr 動態的添加屬性
def method():
print("cow")
setattr(foo, "type", "cow")
setattr(foo, "getcow", method)
# cow
foo.type
foo.getcow()
# 動態刪除屬性 delattr
delattr(foo, "type")
# getattr 獲取成員屬性
if hasattr(foo, "run"): # 判斷是否有屬性
func = getattr(foo, "run")
func()