python基础之类(class)以及元类(metaclass)的概念

类的一些概念:
首先在明白metaclass前,我们需要明白python中类的概念。在许多语言中,类仅仅是一段可以生成对象的代码;
1,例如:
>>> class c1(object):
...     pass
...
>>>
>>>
>>> test_class = c1()
>>>
>>> print(test_class)
<__main__.c1 object at 0x0000024A5CBCC2E8>
在python中,类不仅仅可以生成对象,而且本身也是一个对象,只是这个对象是可以创建对象的,它可以做对象可以做的事,例如:
1)给它赋值给变量
2)可以拷贝
3)可以添加属性
4)可以作为函数参数
>>> print(c1)
<class '__main__.c1'>   #可以打印出来,因为它是对象
>>> def test(f):       #作为函数参数的情况
...     print(f)
...
>>> test(c1)
<class '__main__.c1'>
>>> c1.newatrr = "atrr1"		#给类添加新的属性
>>> print(hasattr(c1,'newatrr'))
True
>>> print(c1.newatrr)		#打印属性的值
atrr1
>>> c1_clone = c1	        #复制类给变量
>>> print(c1_clone.newatrr)
atrr1
>>> print(c1_clone)	        #打印该变量,新的类c1_clone还是c1类,并没有创建新类
<class '__main__.c1'>
2,动态创建类
>>> print(type(1))
<class 'int'>
>>> print(type('1'))
<class 'str'>
>>> print(type(c1))
<class 'type'>
>>> print(type(c1()))
<class '__main__.c1'>
从中可以看到type()可以返回一个class,因此我们可以使用type类动态构建类。查看帮助,得到:
>>> help(type)
Help on class type in module builtins:

class type(object)
 |  type(object_or_name, bases, dict)
 |  type(object) -> the object's type
当1个参数的时候,返回对象的类型,暂时不考虑;3个参数的时候class type(name, bases, dict),创建一个新的对象。
type(name of the class--name,
         tuple of the parent class (for inheritance, can be empty)--bases,
         dictionary containing attributes names and values--dict)
例子:
>>> class c2(object):
...     bar = True
...
>>>
>>> Foo = type('Foo',(),{'bar':True})
>>> print(Foo)
<class '__main__.Foo'>
>>> f = Foo()
>>> print(f)
<__main__.Foo object at 0x0000024A5CBCCC18>
>>> print(f.bar)
True
用type创建FooChild类继承Foo类:
>>> FooChild = type('FooChild',(Foo,),{})		#创建子类对象
>>> print(FooChild)
<class '__main__.FooChild'>		
>>> print(FooChild.bar)
而如果想动态增加新的function,怎么办;我们可以先定义好function,然后将这个function当作属性,同样的使用type添加到FooChild类中,例子如下:
>>> def f1(self):
...     print('add new function to test')
...
>>> def f1(self):
...     print(self.bar)
...
>>> FooChild = type('FooChild',(Foo,),{'f1':f1})
>>> hasattr(Foo,'f1')
False
>>> foochild = FooChild()
>>> foochild.f1()
还可以直接将fuction,像常规增加属性的样子,直接赋值:
>>> def f2(self):
...     print('test test')
...
>>> FooChild.f2 = f2
>>> hasattr(FooChild,'f2')
以上说的python中类是一个对象,究其原因是因为它是由元类实现的。
元类的概念:
元类是一个类的类,就像类定义了实例的行为,元类定义了类的行为。一个类是元类的实例。可以称为工厂类。

    未完待续......

猜你喜欢

转载自blog.csdn.net/mucangmang/article/details/79595357