特殊属性dir
__dir__
- import导入什么到当前模块dir()的属性里面就多显示什么(见例1)
- dir()收集类的所有属性,包括继承类(祖先类)见例2
例1:
class A:
def __init__(self):
self.a = 5
print('in 01',dir())
a = A()
from zs01 import A
class B:
def __init__(self,b):
self.b = b
# def __dir__(self):
# return '666'
x= 100
print('in 02 {}'.format(__name__),dir())
显示信息:
in 01 ['A', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
in 02 __main__ ['A', 'B', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'x']
例2
print(dir(B))
print(sorted(B.__dict__.keys() | zs01.A.__dict__.keys() | object.__dict__.keys()))
实例化一个类,dir(?),会显示什么?
显示类的属性和实例的属性,因为调用的super,所有也显示父类的实例属性
例3
import zs01
print('01 ',dir(zs01))
class B(zs01.A):
def __init__(self,b):
super().__init__(b)
self.c = 100
print(dir(c))
打印信息:
['__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__', 'a', 'c']