元类
首先,类也是一种对象,只要使用关键字class,python解释器在执行的时候就会创建一个对象。你就可以给他赋值一个变量、拷贝它、增加属性、将它作为函数参数进行传递。
使用type创建类
type可以动态的创建类,它可以接受一个类的描述作为参数,然后返回一个类。
使用方法:type(类名,由父类名称组成的元组(可以为空),包含属性的字典)
来看一个实例:
```python
test = type("test",(),{})#定义一个test类
a = test()#创建一个test类的实例对象
print(a)
print(test)
```
输出结果:
使用type创建带有属性的类
type接受一个字典来为类定义属性:
```python
Test = type('Test',(),{'flag':True})
```
可以翻译为:
```python
class test(object):
flag=True
print(test)
print(test.flag)
```
输出结果:
也可以向这个类继承:
```python
test = type("test",(),{})#定义一个test类
class test:
flag = True
test2 = type('test2',(test,),{})
print(test2)
print(test2.flag)
```
输出结果:
使用type创建带有方法的类
添加实例方法
```python
test = type("test",(),{})#定义一个test类
class test:
flag = True
def echo_bar(self):
print(self.bar)
test2 = type('test2',(test,),{'echo_bar':echo_bar})
a = hasattr(test,'echo_bar')#判断test类中,是否有echo_bar这个属性方法
print(a)
b = hasattr(test2,'echo_bar')#判断test2类中,是否有echo_bar这个属性方法
print(b)
```
输出结果:
添加静态方法
```python
test = type("test",(),{})#定义一个test类
class test:
flag = True
def echo_bar(self):
print(self.bar)
@staticmethod
def testStatic():
print("test staticmethod")
test2 = type('test2',(test,),{'echo_bar':echo_bar,'testStatic':testStatic})
test2.testStatic()
```
输出结果:
添加类方法
```python
test = type("test",(),{})#定义一个test类
class test:
flag = True
def echo_bar(self):
print(self.bar)
@classmethod
def testClass(cls):
print("test class method")
test2 = type('test2',(test,),{'echo_bar':echo_bar,'testClass':testClass})
test2.testClass()
```
输出结果: