开发者

dir() a __class__ attribute?

开发者 https://www.devze.com 2023-03-17 11:54 出处:网络
class Foo: pass >>> f = test.Foo() Lets look into the class instance ... >>> dir(f) [\'__add__\', [__class__] ...]
class Foo:
  pass

>>> f = test.Foo()

Lets look into the class instance ...

>>> dir(f)
['__add__', [__class__] ...]

Oooh! Lets look into the class instance metadata ...

>>> dir(f.__class__)
['__add__', [__class__] ...]

hmm ... was expecting attributes of __class__ ; but returns back attributes of f

Trying a hit and trial ...

>>> dir(f.__class__.__class__)
['__abstractmethods__', '__ba开发者_如何学Gose__' ...]

hmm ... why twice a charm?


dir(f) and dir(f.__class__) are showing the attributes of two different things. It's just that your empty object has the same attributes as its own class. Try this:

>>> class Foo:
...  def __init__(self):
...   self.a = 17
...
>>> f = Foo()
>>> 'a' in dir(f)
True
>>> 'a' in dir(f.__class__)
False
0

精彩评论

暂无评论...
验证码 换一张
取 消