Python每天五分鐘-面向對象編程之對象
- 2019 年 12 月 17 日
- 筆記
對象
這裡說的對象可不是一對象棋中的象

對象其實就是類的實例化,稱之為對象。

其實在Python中數據也可以稱之為一個對象比如字元串。
字元串對象
s = 'abcdef' print(s.__len__()) # 輸出結果 6 # 上面這段程式碼等價於 len(s)
獲取對象的屬性及方法
使用dir(obj)
print(dir(s)) # 輸出結果 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
實例屬性與類屬性
實例屬性就是在類外部定義的屬性,如果與類屬性同名會屏蔽掉類屬性的值。
class Person(object): name = 'person' l = Person() l.name = 'lilei' print(l.name) print(Person.name) # 輸出結果 # lilei # person
如果將實例的屬性刪除,會引用類屬性
l = Person() l.name = 'lilei' del l.name print(l.name) # 輸出結果 # person