考慮一下:獲得所有屬性到達從一個模塊或其它任何物體
>>> import math
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
__dict__
沒有列出,但我仍然可以做
>>> math.__dict__
同樣的事情
>>> class MyClass(object):
def __init__(self, var1, var2):
self.a = var1
self.b = var2
def __call__(self, arg):
print " The arg passed is ", arg
>>> dir(MyClass)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
__bases__
和__base__
未列出,但我仍可以這樣做:
>>> MyClass.__bases__
(<type 'object'>,)
>>> MyClass.__base__
<type 'object'>
問:
我怎麼能知道或者提前告訴從Python對象可到達的所有屬性?在這種情況下,我怎麼能告訴math
模塊有__dict__
和MyClass
有__base__
和__bases__
?
'dir(type(MyClass))'會顯示它們。 Metaclass屬性通常對'dir'隱藏。與'Myclass.mro()'同樣的事情。 – JBernardo
順便說一句,你可以定義你自己的'__dir__'方法,並返回隨機的名字,如果你想... – JBernardo
@JBernardo什麼是mro()? – abc