Python 简明教程

Python - Anonymous Class and Objects

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

Python’s built-in type() function returns the class that an object belongs to. In Python, a class, both a built-in class or a user-defined class are objects of type class.

Example

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))

它将生成以下 output

It will produce the following output

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

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

The type() has a three argument version as follows −

Syntax

newclass=type(name, bases, dict)

使用上述语法,可以动态创建类。type 函数的三个参数是 −

Using above syntax, a class can be dynamically created. Three arguments of type function are −

  1. name − name of the class which becomes name attribute of new class

  2. bases − tuple consisting of parent classes. Can be blank if not a derived class

  3. dict − dictionary forming namespace of the new class containing attributes and methods and their values.

Create an Anonymous Class

我们可以使用 type() 函数的上述版本创建一个匿名类。名称参数为 null string ,第二个参数是单个类的 tuple (object)类(请注意,Python 中的每个类都从 object 类继承)。我们添加某些实例变量作为第三个参数 dictionary 。我们现在将其保留为空。

We can create an anonymous class with the above version of type() function. The name argument is a null string, second argument is a tuple of one class the object class (note that each class in Python is inherited from object class). We add certain instance variables as the third argument dictionary. We keep it empty for now.

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

Create an Anonymous Object

要创建此匿名类的对象 −

To create an object of this anonymous class −

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

结果表明对象属于匿名类

The result shows that the object is of anonymous class

type of obj: <class '__main__.'>

Anonymous Class and Object Example

我们也可以动态添加实例变量和实例方法。请看此示例 −

We can also add instance variables and instance methods dynamically. Take a look at this example −

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())

它将生成以下 output

It will produce the following output

5 6