class Person():
name = "Tim"
class Animal(object):
name = "Anaconda"
if __name__ == "__main__":
x = Person()
print(f"class: Person \n {dir(x)} \n len(dir(x)) = {len(dir(x))} \n")
y = Animal()
print(f"class: Animal \n {dir(y)} \n len(dir(y)) = {len(dir(y))} \n")
print(f"dir(x) == dir(y): {dir(x) == dir(y)}")
输出如下:
class: Person
['__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__', 'name']
len(dir(x)) = 27
class: Animal
['__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__', 'name']
len(dir(y)) = 27
dir(x) == dir(y): True
由上,python3 默认继承 object 类,拥有完全相同的类属性。定义 class 时,可以不加 object