Python 匿名类和对象

Python 匿名类和对象

Python内置的type()函数返回对象所属的类。在Python中,无论是内置类还是用户定义的类都是类型为class的对象。

示例

class myclass:
   def __init__(self):
      self.myvar=10
      return

obj = myclass()

print ('class of int', type(int))
print ('class of list', type(list))
print ('class of dict', type(dict))
print ('class of myclass', type(myclass))
print ('class of obj', type(obj))
Python

这将产生以下 输出

class of int <class 'type'>
class of list <class 'type'>
class of dict <class 'type'>
class of myclass <class 'type'>
Python

type()有三个参数版本,如下所示:

语法

newclass=type(name, bases, dict)
Python

使用上述语法,可以动态创建一个类。三个类型为函数的参数是:

  • name - 成为新类的__name__属性的类名

  • bases - 由父类组成的元组。如果不是派生类,则可以为空

  • dict - 构成新类的命名空间的字典,包含属性、方法及其值。

我们可以使用上述版本的type()函数创建一个匿名类。name参数是一个空字符串,第二个参数是一个包含一个类的元组,该类是对象类的一个实例(请注意,Python中的每个类都继承自对象类)。我们在第三个参数字典中添加一些实例变量。目前将其保持为空。

anon=type('', (object, ), {})
Python

创建该匿名类的对象的方法如下:

obj = anon()
print ("type of obj:", type(obj))
Python

结果显示该对象属于匿名类

type of obj: <class '__main__.'>
Python

示例

我们还可以动态地添加实例变量和实例方法。看一下这个例子-

def getA(self):
   return self.a
obj = type('',(object,),{'a':5,'b':6,'c':7,'getA':getA,'getB':lambda self : self.b})()
print (obj.getA(), obj.getB())
Python

它将产生以下 输出

5 6
Python

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册