This article mainly introduces the class and object learning tutorials in Python object-oriented programming. object-oriented is the basic feature of Python, the features and usage of classes and objects are the basic skills in Python learning. if you need them, you can refer to everything in Python as an object. Class provides a mechanism to create new types of objects. In this tutorial, we will not talk about the basic knowledge of class and object-oriented programming, but focus on a better understanding of Python object-oriented programming. Suppose we use the new python classes that inherit from the object parent class.
Definition class
Class statements can define a series of attributes, variables, and methods that are shared by instance objects of the class. The following is a simple class definition:
class Account(object): num_accounts = 0 def __init__(self, name, balance): self.name = name self.balance = balance Account.num_accounts += 1 def del_account(self): Account.num_accounts -= 1 def deposit(self, amt): self.balance = self.balance + amt def withdraw(self, amt): self.balance = self.balance - amt def inquiry(self): return self.balance
Class definition introduces the following new objects:
Class object
Instance object
Method object
Class object
When a class definition is encountered during program execution, a new namespace is created. the namespace contains all class variables and the name of the method definition is bound. Note that the namespace does not have a new local scope that can be used to create a class method. Therefore, you must specify a fully qualified name to access the variable in the method. The Account class in the previous section demonstrates this feature. to access the num_of_accounts variable, you must use the fully qualified Account name. num_of_accounts. Otherwise, if the fully qualified name is not used in the _ init _ method, the following error is thrown:
class Account(object): num_accounts = 0 def __init__(self, name, balance): self.name = name self.balance = balance num_accounts += 1 def del_account(self): Account.num_accounts -= 1 def deposit(self, amt): self.balance = self.balance + amt def withdraw(self, amt): self.balance = self.balance - amt def inquiry(self): return self.balance >>> acct = Account('obi', 10)Traceback (most recent call last): File "python", line 1, in
File "python", line 9, in __init__UnboundLocalError: local variable 'num_accounts' referenced before assignment
At the end of the class definition execution, a class object is created. The effective scope before entering the class definition is now restored, and the class object is bound to the class name of the class definition header.
First, you may ask what is the class of the class object if the created class is an object ?. The same as the python philosophy of object, class object does have a class, that is, type class in the new python style class.
>>> type(Account)
To be more confused, the Account type is type. The type class is a Metaclass used to create other classes. we will introduce it later in the tutorial.
Class objects support attribute reference and instantiation. The property is referenced by standard point syntax, that is, the object is followed by a period, and then the property name is obj. name. Valid attribute names are all the variables and method names that appear in the class namespace after the class object is created. For example:
>>> Account.num_accounts>>> 0>>> Account.deposit>>>
Class instantiation uses function notation. Instantiation will call class objects without parameters like normal functions, the Account class in the following text:
>>> Account()
After the class object is instantiated, the instance object is returned. if The _ init _ method is defined in the class, it is called and the instance object is passed as the first parameter. This method initializes user-defined initialization processes, such as instance variables. For example, the Account name and balance are set, and the number of instance objects increases by 1.
Instance object
If the class object is a cookie cutter, the biscuit is the result of instantiating the class object. All valid operations on instance objects are references to properties, data, and method objects.
Method object
The method object is similar to the function object. If x is an Account instance, x. deposit is an example of a method object. There is an additional parameter in the method definition, self. Self points to the class instance. Why do we need to pass the instance as a parameter to the method? Method call can be best described as follows:
>>> x = Account()>>> x.inquiry()10
What happens when an instance method is called? You should note that x. inquiry () does not have any parameters when calling, although the method definition contains the self parameter. So what happened to this parameter?
The special feature is that the object used by the method is passed as the first parameter of the function. In our example, calling x. inquiry () is equivalent to Account. f (x ). Generally, the method that calls the n parameter is equivalent to inserting the object of the method to the first parameter.
Python tutorial:
When the referenced instance property is not a data property, the search class is used. If the name represents a valid function object, the instance object and function object will be packaged into an abstract object, that is, the method object. When a method object containing the parameter list is called, a new parameter list is created based on the instance object and parameter list, and the function object is called using the new parameter list.
This applies to all instance method objects, including the _ init _ method. The self parameter is not a keyword. any valid parameter name can be used, as shown in the following Account class definition:
class Account(object): num_accounts = 0 def __init__(obj, name, balance): obj.name = name obj.balance = balance Account.num_accounts += 1 def del_account(obj): Account.num_accounts -= 1 def deposit(obj, amt): obj.balance = obj.balance + amt def withdraw(obj, amt): obj.balance = obj.balance - amt def inquiry(obj): return obj.balance >>> Account.num_accounts>>> 0>>> x = Account('obi', 0)>>> x.deposit(10)>>> Account.inquiry(x)>>> 10
Static and class methods
The method defined in the class is called by the instance by default. However, we can also use the corresponding @ staticmethod and @ classmethod decorators to define static or class methods.
Static method
Static Mode is a common function in a namespace class. The static method of the reference class returns the function type, rather than the non-bound method type:
class Account(object): num_accounts = 0 def __init__(self, name, balance): self.name = name self.balance = balance Account.num_accounts += 1 def del_account(self): Account.num_accounts -= 1 def deposit(self, amt): self.balance = self.balance + amt def withdraw(self, amt): self.balance = self.balance - amt def inquiry(self): return "Name={}, balance={}".format(self.name, self.balance) @staticmethod def type(): return "Current Account" >>> Account.deposit
>>> Account.type
Use the @ staticmethod modifier to define static methods. these methods do not require the self parameter. Static methods can better organize class-related code or rewrite them in subclass.
Class method
A class method is called by the class itself, rather than an instance. The class method is defined using the @ classmethod modifier. The first parameter is passed to the class rather than the instance of the method.
import json class Account(object): num_accounts = 0 def __init__(self, name, balance): self.name = name self.balance = balance Account.num_accounts += 1 def del_account(self): Account.num_accounts -= 1 def deposit(self, amt): self.balance = self.balance + amt def withdraw(self, amt): self.balance = self.balance - amt def inquiry(self): return "Name={}, balance={}".format(self.name, self.balance) @classmethod def from_json(cls, params_json): params = json.loads(params_json) return cls(params.get("name"), params.get("balance")) @staticmethod def type(): return "Current Account"
A common usage of class methods is to create a factory as an object. Assume that there are many types of Account data formats, such as tuples and json strings. Since Python classes can only define one _ init _ method, class methods are very convenient in these cases. The above Account class is used as an example. we want to initialize an Account based on a json string object. we define a class Factory method from_json, which reads the json string object and parses parameters, create an account object based on parameters. Another example of a class instance is the dict. fromkeys method, which creates a dict object from a set of key and value sequences.
Python special method
Sometimes we want to customize the class. This requires changing the method for creating and initializing class objects, or providing multi-state behavior for some operations. Polymorphism allows you to customize the implementation of some python operations such as ++ in the class definition. The special methods of Python can do this. These methods are generally in the _ * _ format, where * indicates the method name. For example, _ init _ and _ new _ customize object creation and initialization, __getitem _, _ get _, _ add _, and _ sub _ to simulate python built-in types, there are also _ getattribute _ and _ getattr _ to customize attribute access. There are only a few special methods. we will discuss some important special methods for a simple understanding. The python documentation has a list of all the methods.
Special methods for object creation
A new class instance is created through a two-phase process. The __new _ method creates a new instance and the __init _ method initializes the instance. You are already familiar with the _ init _ method definition. However, you rarely define the _ new _ method. However, you can also create a custom class instance.
Special methods for attribute access
You can use the following methods to customize the attribute access of a class instance.
class Account(object): num_accounts = 0 def __init__(self, name, balance): self.name = name self.balance = balance Account.num_accounts += 1 def del_account(self): Account.num_accounts -= 1 def __getattr__(self, name): return "Hey I dont see any attribute called {}".format(name) def deposit(self, amt): self.balance = self.balance + amt def withdraw(self, amt): self.balance = self.balance - amt def inquiry(self): return "Name={}, balance={}".format(self.name, self.balance) @classmethod def from_dict(cls, params): params_dict = json.loads(params) return cls(params_dict.get("name"), params_dict.get("balance")) @staticmethod def type(): return "Current Account" x = Account('obi', 0)
_ Getattr _ (self, name) __: this method is called only when the name is neither an instance attribute nor is found in the class inheritance chain of the object. This method should return the property value or cause AttributeError. For example, if x is an Account instance, this method is called when you try to access a non-existent property.
>>> acct = Account("obi", 10)>>> acct.numberHey I dont see any attribute called number
Note that if _ getattr _ references an instance attribute that does not exist, an endless loop may occur because the _ getattr _ method is continuously called.
2. _ setattr _ (self, name, value) __: this method is called when an attribute value assignment occurs. _ Setattr _ inserts the value into the instance attribute dictionary, instead of using self. name = value, because it will lead to an endless loop of recursive calls.
3. _ delattr _ (self, name) __: called when del obj occurs.
4. _ getattribute _ (self, name) __: this method is always called to implement attribute access for class instances.
Special methods for type simulation
For some types, Python defines some specific syntaxes. for example, the list and element of the group can be accessed through index notation, and the value can be added through the + operator. We can create our own classes that use these special syntaxes. when the python interpreter encounters these special syntaxes, it will call our implementation method. We will use a simple example below to demonstrate this feature, which simulates the basic usage of the python list.
class CustomList(object): def __init__(self, container=None): # the class is just a wrapper around another list to # illustrate special methods if container is None: self.container = [] else: self.container = container def __len__(self): # called when a user calls len(CustomList instance) return len(self.container) def __getitem__(self, index): # called when a user uses square brackets for indexing return self.container[index] def __setitem__(self, index, value): # called when a user performs an index assignment if index <= len(self.container): self.container[index] = value else: raise IndexError() def __contains__(self, value): # called when the user uses the 'in' keyword return value in self.container def append(self, value): self.container.append(value) def __repr__(self): return str(self.container) def __add__(self, otherList): # provides support for the use of the + operator return CustomList(self.container + otherList.container)
In the preceding example, CustomList is a simple package with a real list. To demonstrate the implementation of some custom methods:
_ Len _ (self): it is called when the len () function is called on the CustomList instance.
>>> myList = CustomList()>>> myList.append(1) >>> myList.append(2)>>> myList.append(3)>>> myList.append(4)>>> len(myList)4
2. _ getitem _ (self, value): used to provide square brackets for CustomList class instances:
>>> myList = CustomList()>>> myList.append(1) >>> myList.append(2)>>> myList.append(3)>>> myList.append(4)>>> myList[3]4
3. _ setitem _ (self, key, value): this parameter is called when a value is assigned to self [key] on a CustomList instance.
>>> myList = CustomList()>>> myList.append(1) >>> myList.append(2)>>> myList.append(3)>>> myList.append(4)>>> myList[3] = 1004>>> myList[3]100
4. _ contains _ (self, key): called during member detection. If this option is included, true is returned; otherwise, false is returned.
>>> myList = CustomList()>>> myList.append(1) >>> myList.append(2)>>> myList.append(3)>>> myList.append(4)>>> 4 in myListTrue
5. _ repr _ (self): called when print is used to print self, the object representation of self is printed.
>>> myList = CustomList()>>> myList.append(1) >>> myList.append(2)>>> myList.append(3)>>> myList.append(4)>>> print myList[1, 2, 3, 4]
6. _ add _ (self, otherList): use the + operator to calculate the call for adding two CustomList instances.
>>> myList = CustomList()>>> otherList = CustomList()>>> otherList.append(100)>>> myList.append(1) >>> myList.append(2)>>> myList.append(3)>>> myList.append(4)>>> myList + otherList + otherList[1, 2, 3, 4, 100, 100]
The example above demonstrates how to customize class behavior by defining some special class methods. You can view the complete list of these custom methods in the Python document. In the next tutorial, we will discuss the special methods and explain the descriptor, an important feature that is widely used in python object-oriented programming.