美文网首页
understanding python object 2023

understanding python object 2023

作者: 9_SooHyun | 来源:发表于2023-03-20 17:27 被阅读0次

classes are objects

the following instruction

>>> class ObjectCreator(object):
...       pass

...creates an object with the name ObjectCreator!
This object (the class) is itself capable of creating objects (called instances).

type to create class objects

type is used to create class objects. It works this way: type(name, bases, attrs)
Where:

name: name of the class
bases: tuple of the parent class (for inheritance, can be empty)
attrs: dictionary containing attributes names and values

eg. create class FooChild:

>>> class Foo(object):
...       bar = True
>>>
>>>
>>> def echo_bar(self):
...       print(self.bar)
...
>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})

type accepts a dictionary to define the attributes of the class. So:

>>> class Foo(object):
...       bar = True

Can be translated to:

>>> Foo = type('Foo', (), {'bar':True})

Metaclass

Metaclasses are the 'stuff' that creates classes

You've seen that type lets you do something like this: MyClass = type('MyClass', (), {})

It's because the function type is in fact a metaclass.

type is the metaclass Python uses to create all classes behind the scenes. type is just the class that creates class objects

type is a metaclass, a class and an instance at the same time

Everything is an object in Python, and they are all either instance of classes or instances of metaclasses.

Except for type. Or, more for type

  • type is an instance of class type itself
>>> isinstance(1, int)
True
>>> type(1)
<class 'int'>
>>>
>>> isinstance(type, type)
True
>>> type(type)
<class 'type'>
  • classtype's metaclass is classtype itself
>>> age = 1
>>> age.__class__
<class 'int'>
>>> age.__class__.__class__
<class 'type'>
>>> 
>>> type.__class__
<class 'type'>
>>> type.__class__.__class__
<class 'type'>

refer to https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python

相关文章

网友评论

      本文标题:understanding python object 2023

      本文链接:https://www.haomeiwen.com/subject/kuxprdtx.html