understanding python object 2023

2023-03-20  本文已影响0人  9_SooHyun

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

>>> isinstance(1, int)
True
>>> type(1)
<class 'int'>
>>>
>>> isinstance(type, type)
True
>>> type(type)
<class 'type'>
>>> 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

上一篇 下一篇

猜你喜欢

热点阅读