A class is a user-defined type that developers can instantiate to obtain an instance. An instance represents an object of this type. In Python, classes are objects, and developers can treat functions just like other objects. They can pass a class as a parameter when calling a function, or they can return a class as the result of a function call. Any object, even a class object, has a type. In Python, types and classes are also first-class objects. The type of a class object is also called the metaclass of the class. The behavior of an object is primarily determined by the type of object of that class. This also applies to classes: the behavior of a class is also primarily determined by its metaclass.
The class statement is the most commonly used method to create a class object. As follows:
class classname(base_classes): statement(s)
classname is an identifier. The identifier is a variable that is bound to the class object after the class statement is executed. base_classes is a comma-separated sequence of expressions whose values must be class objects. For example:
class C(B1,B2): #B1和B2都是类 statement(s)
Finally, please note that the class statement does not directly create any instance of the new class, but defines the set of properties common to all instances (i.e., class object) when this class is called to create an instance in the future. Attributes).
You can usually specify an attribute of a class object (i.e., class attribute) by binding a value to an identifier in the class body. For example:
class C1(object): x = 23print C1.x #print:23
Class object C1 contains a property named x, which is bound to the value 23. We should know that any class attribute is implicitly shared by all instances of that class when an instance is created.
Class objects will implicitly set certain class attributes. The attribute __name__ is a class name identifier string. The attribute __bases__ is a tuple of class objects of the base class of the class. For example:
print C1.__name__, C1.__bases__ #print: C1, ()
The class object also contains an attribute __dict__, which is the dictionary object of the class and is used to save all other attributes. For any class object C, any object x, and any identifier S (except __name__, __bases__, and __dict__), C.S is equal to C.__dict__[‘S’] = x. For example:
C1.y = 45C1.__dict__['z']= 67print C1.y,C1z #print: 45, 67
An instance of a class is a Python object with properties of any name that developers can bind and reference. To create an instance of a class, you call the class object as if the object were a function. Each call will return a new instance of type:
anInstance = C1()
Developers can call the built-in function isinstance(I, C) and use a class object as parameter C. instance will return True if object I is an instance of class C or any subclass of class C, otherwise it will return False.
When a class defines or inherits a method named __init__, calling the class object will implicitly execute the __int__ method on the new instance to perform any required Instance-related initialization. The parameters passed in this call must correspond to the parameters of __init__, except for the parameter self. For example:
class C6(objec): def __init__(self, n); self.x = n
Create an instance of class C6:
anInstance = C6(42)
The main purpose of __init__ is to bind, and therefore create, the properties of the newly created instance. The __init__ method cannot return a value, otherwise Python will raise a TypeError exception.
For any instance z, z..__class__ is the class object to which z belongs, and z..__dict__ is the dictionary used by z to save other attributes. For example:
print anInstance.__classs__.__name__, anInstance .__dict__ #print: C6, {'x' : 42}
For any instance z, any object x, and any identifier S (except __classs and __dict__), z.S = x is equal to z.__dict__[‘S’] = x. For example:
z.y = 45z.__dict__['z'] = 67print z.y, z.z #print: 45, 67
Each new type of library has (or inherits) a static method named __new__. When a developer calls C(*args, **kwds) to create an instance of class C, Python will first call C.__new__(C,*args, **kwds). Python uses the return value x of __new__ as the newly created instance. Then, Python will call C.__init__(x,*args, **kwds), but this method will only be called when x is confirmed to be an instance of C, or any subclass of C. For example: the statement x = C(23) is equivalent to:
x = C.__new__(C, 23)if isinstance(x, C): type(x).__init__(x, 23)
object.__new__ can create a new and uninitialized instance of the class it accepts as the first argument. If this class contains an __init__ method, the method will ignore other parameters, but if the method accepts other parameters in addition to the first parameter, and the first parameter's class does not contain an __init__ method, then This method will throw an exception. The above content is demonstrated below by implementing the Singleton design pattern.
class Singleton(object): ## @var __Instance __Instance = None @staticmethod def GetInstance(): if Singleton.__Instance == None: Singleton.__Instance = Singleton() return Singleton.__Instance def __new__(cls, *args, **kv): print "__new__" if Singleton.__Instance == None: Singleton.__Instance = object.__new__( cls ) print "Singleton.__Instance:", Singleton.__Instance return Singleton.__Instance def __init__(self, x): print "__init__" print "self:", self self.x = x print x def PrintX(self): print self.x anInstance = Singleton(23) anotherInstance = Singleton(32)
从上面运行结果我们可以看出,创建一个新实例时,先调用new方法,再调用init方法。单实例通过重写new方法,第二次实例化时,new返回上次的实例,然后该实例再次调用init方法。
类(class)是一个用户自定义类型,开发者可以将其实例化以获得实例(instance),实例表示这种类型的对象。在Python中,类就是对象,开发者可以像对其他对象那样处理函数,可以在调用函数时传递一个类作为参数,也可以返回一个类作为函数调用的结果。任何对象,即使是一个类对象,都有一个类型。在Python中,类型和类也都是第一类对象。类对象的类型也被称为该类的元类(metaclass)。对象的行为主要是由该类对象的类型确定的。这也适用于类:类的行为也是主要由该类的元类确定的。
class语句是创建一个类对象最常用的方法。如下:
class classname(base_classes): statement(s)
classname是一个标识符。该标识符是一个在执行完class语句之后被绑定到类对象的变量。base_classes是一个使用逗号分隔的表达式序列,这些表达式的值必须是类对象。例如:
class C(B1,B2): #B1和B2都是类 statement(s)
最后,请注意,class语句并不直接创建新类的任何一个实例,而是定义了在以后调用这个类创建实例时,所有实例共有的属性集(即类对象属性)。
通常可以通过将一个值绑定到类体中的一个标识符上来指定类对象的一个属性(即类属性)。例如:
class C1(object): x = 23print C1.x #print:23
类对象C1包含一个名为x的属性,该属性被绑定为值23。我们应该知道,在实例被创建时,任何类属性都由该类的所有实例隐式共享。
类对象会隐式设置某些类属性。属性__name__是类名标识符字符串。属性__bases__是类的基类的类对象的元组。例如:
print C1.__name__, C1.__bases__ #print: C1, ()
类对象还包含一个属性__dict__,这个属性是该类的字典对象,被用来保存所有其他属性。对于任何类对象C、任何对象x,以及任何标识符S(除了__name__、__bases__和__dict__),C.S等于C.__dict__[‘S’]=x。例如:
C1.y = 45C1.__dict__['z']= 67print C1.y,C1z #print: 45, 67
类的实例是一个带有任意名称的属性的Python对象,开发者可以绑定和引用这些属性。要想创建一个类的实例,可以调用类对象,就像该对象是一个函数一样。每个调用都将返回一个类型为该类的新实例:
anInstance = C1()
开发者可以调用内置函数isinstance(I, C),并使用一个类对象作为参数C。如果对象I是类C或类C的任何子类的一个实例,则instance将返回True,否则返回False。
当一个类定义或继承了一个名为__init__的方法时,调用该类对象将对新实例隐式执行__int__方法以执行任何需要的与实例相关的初始化。该调用中传递的参数必须对应于__init__的参数,除了参数self。例如:
class C6(objec): def __init__(self, n); self.x = n
创建类C6的一个实例:
anInstance = C6(42)
__init__的主要目的就是绑定,并因此创建新创建的实例的属性。__init__方法不能返回一个值,否则,Python将引发一个TypeError异常。
对于任何实例z,z..__class__是z所属的类对象,而z..__dict__是z用来保存其他属性的字典。例如:
print anInstance.__classs__.__name__, anInstance .__dict__ #print: C6, {'x' : 42}
对于任何实例z,任何对象x和任何标识符S(除了__classs和__dict__),z.S = x等于z.__dict__[‘S’] = x。例如:
z.y = 45z.__dict__['z'] = 67print z.y, z.z #print: 45, 67
每个新型累都有(或者继承了)一个名为__new__的静态方法。当开发者调用C(*args, **kwds)来创建类C的一个实例时,Python将首先调用C.__new__(C,*args, **kwds)。Python使用__new__的返回值x作为新创建的实例。然后,Python将调用C.__init__(x,*args, **kwds),但是只有在x确认是C的一个实例,或者C的任何一个子类时才会调用该方法。例如:语句x = C(23)等同于:
x = C.__new__(C, 23)if isinstance(x, C): type(x).__init__(x, 23)
object.__new__可以创建其接受为第一个参数的类的一个新的和未初始化的实例。如果这个类包含一个__init__方法,则该方法将忽略其他参数,但是,如果除了第一个参数,该方法还接受了其他参数,并且第一个参数的类不包含__init__方法,则该方法将引发一个异常。下面通过实现Singleton设计模式来演示上面内容。
class Singleton(object): ## @var __Instance __Instance = None @staticmethod def GetInstance(): if Singleton.__Instance == None: Singleton.__Instance = Singleton() return Singleton.__Instance def __new__(cls, *args, **kv): print "__new__" if Singleton.__Instance == None: Singleton.__Instance = object.__new__( cls ) print "Singleton.__Instance:", Singleton.__Instance return Singleton.__Instance def __init__(self, x): print "__init__" print "self:", self self.x = x print x def PrintX(self): print self.x anInstance = Singleton(23) anotherInstance = Singleton(32)
从上面运行结果我们可以看出,创建一个新实例时,先调用new方法,再调用init方法。单实例通过重写new方法,第二次实例化时,new返回上次的实例,然后该实例再次调用init方法。
The above is the detailed content of Detailed explanation of examples of Python classes. For more information, please follow other related articles on the PHP Chinese website!