[英]What is the difference between object vs type as base classes?
I would usually initialize a class this way,我通常会这样初始化 class,
class C:
pass
but if I do something like this,但如果我这样做,
class A(object):
pass
and if I do,如果我这样做,
class B(type):
pass
then, if I run,那么,如果我跑,
dir(A)
it gives me this list,它给了我这个列表,
['__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__']
while尽管
dir(B)
gives me this list,给我这份清单,
['__abstractmethods__', '__base__', '__bases__', '__basicsize__', '__call__',
'__class__', '__delattr__', '__dict__', '__dictoffset__', '__dir__', '__doc__',
'__eq__', '__flags__', '__format__', '__ge__', '__getattribute__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__instancecheck__',
'__itemsize__', '__le__', '__lt__', '__module__', '__mro__', '__name__',
'__ne__', '__new__', '__prepare__', '__qualname__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasscheck__', '__subclasses__', '__subclasshook__',
'__text_signature__', '__weakrefoffset__', 'mro']
but I can use these on class A
also, for example, I can use A.__bases__
, A.mro
, although it is not listed in dir(A)
但是我也可以在 class
A
上使用这些,例如,我可以使用A.__bases__
, A.mro
,尽管它没有在dir(A)
中列出
A.mro, A.__bases__
gives,给,
(<function A.mro>, (object,))
while,尽管,
B.mro, B.__bases__
gives,给,
(<method 'mro' of 'type' objects>, (type,))
Furthermore, when I create instances, then,此外,当我创建实例时,
# both have object as base class
a = A()
c = C()
works, but,有效,但是,
# type as base class
b = B()
gives this error,给出这个错误,
TypeError: type.__new__() takes exactly 3 arguments (0 given)
It appears that by default object
is the base class, but I still am confused when exactly should I specify, type
as a base class?似乎默认情况下
object
是基数 class,但我仍然很困惑我应该在什么时候指定, type
基数 class? And what more differences are there between the two?两者之间还有什么区别?
it appears that as soon as I specify type
as the base class, my class becomes a class creator.看来,一旦我将
type
指定为基础 class,我的 class 就变成了 class 创建者。 so, instances of a class with type
as the base class, will be classes.因此,
type
为 class 的 class 的实例将是类。 that is,那是,
# with type as base class
b = B()
would give an error,会报错,
TypeError: type.__new__() takes exactly 3 arguments (0 given)
but,但,
b = B('B', (object,), {})
would work, and now, b
itself is a class, and I can create instances of it会工作,现在,
b
本身是一个 class,我可以创建它的实例
d = b()
type(d)
gives,给,
__main__.B
whereas, if I specified,而如果我指定,
b = B('B', (type,), {})
then b
is again a class creator, and instances of it will be classes themselves.那么
b
又是一个 class 的创建者,它的实例本身就是类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.