[python]使用type创建类

本文主要说明如何使用type来创建类,并添加类属性、方法。

type实则是python内建元类,用来创建 类,当我们用class 定义一个类时,python后台是在用type创建该类。

了解type的两种用法

class type(object)
 |  type(object) -> the object's type
 |  type(name, bases, dict) -> a new type

创建A类,具有A.addr属性

>>> A = type('A', (), {'addr':'beijing'})
>>> A
<class '__main__.A'>

定义一个函数,作为类方法的引用

>>> def sayhello(self):
...     print('hello, {}!'.format(self.addr))
... 

创建B类,继承A,属性中添加 greeting方法,引用之前定义的函数

>>> B = type('B', (A,), {'greeting': sayhello})
>>> B
<class '__main__.B'>

B.greeting属性存在,且是一个函数(方法);

不能以类来调用该方法;

>>> B.greeting
<function sayhello at 0x10fc90158>
>>> B.greeting()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sayhello() missing 1 required positional argument: 'self'

以类的实例来调用该方法

>>> b = B()
>>> b.greeting()
hello, beijing!

猜你喜欢

转载自www.cnblogs.com/luxifa/p/9782408.html