class Foo(object):
pass
上面的类是一个“新式”类,因为它继承自object班级。新式类提供了许多“旧式”类所没有的额外框架。新式类的一个特殊属性是能够通过以下方式确定该类的子类:__子类__ method.
有some https://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python good http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes 讨论 http://bytes.com/topic/python/answers/28893-what-status-__subclasses__-method关于新式课堂和__子类__完全使用的方法无证的 http://docs.python.org/release/2.6.4/library/stdtypes.html#class.__subclasses__. ( Here http://mail.python.org/pipermail/python-list/2003-August/210297.html不过,这是蒂姆·彼得斯的非官方解释。 )
“每个新式类都保留对其直接子类的弱引用列表。此方法返回所有仍然活动的引用的列表。”
因此,为了回答你的问题,__子类__功能不可用,因为在您的第二个示例中:
class Foo():
pass
旧式类 Foo 不继承自object(所以它不是一个新式类)并且 for 不继承__子类__ method.
请注意,如果您不明白为什么旧式类没有__子类__你总是可以启动 python 解释器并进行一些检查的方法dir
>>> class Foo(object):
... pass
...
>>> dir(Foo.__class__)
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__', '__class__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', '__
eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__instancecheck__', '__itemsize__', '__le__', '__lt
__', '__module__', '__mro__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__s
ubclasscheck__', '__subclasses__', '__subclasshook__', '__weakrefoffset__', 'mro']
>>> class Bar():
... pass
...
>>> dir(Bar.__class__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class Bar has no attribute '__class__'
>>> dir(Bar)
['__doc__', '__module__']
>>> dir(Foo)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '
__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']