Class and object learning tutorials in Python object-oriented programming

Source: Internet
Author: User
Tags python list
Everything in Python is an object. class provides a mechanism for creating new types of objects. In this tutorial, we don't talk about the basics of class and object-oriented, but focus on a better understanding of Python's object-oriented programming. Let's say we use the new style Python class, which inherits from the object parent class.
Defining Classes

The class statement can define a series of properties, variables, methods, and they are shared by instance objects of the class. A simple class definition is given below:

Class Account (object):  num_accounts = 0   def __init__ (self, Name, balance): = 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

The 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, and the namespace contains the name bindings for all class variables and method definitions. Note that the namespace does not create a new local scope that the class method can use, so accessing the variable in the method requires a fully qualified name. The account class in the previous section demonstrates this feature, and the method that attempts to access the num_of_accounts variable needs to use the fully qualified name account.num_of_accounts, otherwise, if the fully qualified name is not used in the __init__ method, The following error is raised:

Class Account (object): num_accounts = 0  def __init__ (self, Name, balance): = name  self.balance = ba Lance  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 (sel f):  return self.balance >>> acct = account (' Obi ', ten) Traceback (most recent call last): File "Python", line 1, in 
   File "Python", line 9, in __init__unboundlocalerror:local variable ' num_accounts ' referenced befor E Assignment

At the end of the class definition execution, a class object is created. The scope that is valid before entering the class definition is now restored, and the class object is bound to the class name of the class definition header.

First off the topic, you might ask, if the class being created is an object, then what is the class of the class object? Consistent with the Python philosophy that everything is an object, the class object does have a class, the type class in the new Python style class.

>>> Type (account)

To make you more confused, the type of account type is. The type class is a meta class that is used to create other classes that we'll cover later in the tutorial.

Class objects support property references and instantiation. The property is referenced by a standard point syntax, that is, the object is followed by a period and then the property name:. A valid property name is any variable and method name that occurs 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 invoke class objects like normal functions without arguments, as in the account class in the following article:

>>> account ()

After the class object is instantiated, the instance object is returned, and if the __init__ method is defined in the class, it is called, and the instance object passes past as the first argument. This method takes a user-defined initialization process, such as initialization of an instance variable. For example, 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 cookie is the result of instantiating the class object. All valid operations on an instance object are references to properties, data, and method objects.
Method Object

Method objects are similar to function objects. If X is an instance of the account class, 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? A method call can best describe:

>>> x = account () >>> X.inquiry () 10

What happens when an instance method is called? You should notice that the X.inquiry () call has no arguments, although the method definition contains the self parameter. So what exactly happened to this parameter?

What is special is that the object that the method acts on is passed in as the first parameter of the function. In our case, the call to X.inquiry () is equivalent to ACCOUNT.F (x). In general, the method of invoking the n parameter is equivalent to inserting the action object of the method into the first parameter position.

The Python tutorial says:

When the referenced instance property is not a data property, the class is searched. If the name represents a valid function object, the instance object and the function object are packaged into an abstract object, which is the method object. When a method object that contains a parameter list is called, a new parameter list is created based on the instance object and the parameter list, and the function object is invoked with the new argument list.

This applies to all instance method objects, including the __init__ method. The self parameter is not actually a keyword, and any valid parameter name can be used, as shown in the Account class definition:

Class Account (object): num_accounts = 0  def __init__ (obj, name, balance): = name  obj.balance = Balan Ce  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 (Ten) >>> 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 define static or class methods through the corresponding @staticmethod and @classmethod adorners.
Static methods

Static mode is a normal function in a class namespace. A static method that references a class returns a function type, not a non-binding method type:

Class Account (object): num_accounts = 0  def __init__ (self, Name, balance): = name  self.balance = ba Lance  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 i Nquiry (self):  return "name={}, balance={}". Format (, self.balance)  @staticmethod def type ():  return "Current Account" >>> account.deposit

Use the @staticmethod adorner to define static methods, which do not require the self parameter. Static methods can better organize the code related to the class, or they can be overridden in subclasses.
Class method

A class method is called by the class itself, not an instance. The class method uses the @classmethod adorner definition, which is passed to the method as the first argument to the class instead of the instance.

Import JSON class Account (object): num_accounts = 0  def __init__ (self, Name, balance): = 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.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 use of class methods is to create factories as objects. If the account class has a number of data formats, such as tuples, JSON strings, and so on. Because Python classes can only define one __init__ method, class methods are convenient in these situations. For example, in this case, 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, parses the parameters, and creates the account object based on the parameters. An example of another class instance is the Dict.fromkeys method, which creates a Dict object from a set of key and value sequences.
Python Special methods

Sometimes we want to customize the class. This requires changing the way that class objects are created and initialized, or providing polymorphic behavior for some operations. Polymorphic behavior allows custom implementations of certain Python operations, such as +, in the class definition. Python's special methods can do this. These methods are generally in the form of __*__, where * represents the method name. such as __init__ and __new__ from defining object creation and initialization, __getitem__, __get__, __add__, __sub__ to emulate Python built-in types, and __getattribute__, __getattr__ And so on to customize property access. There are only a few special methods, we discuss some important special methods to make a simple understanding, Python document has a list of all methods.
Special methods for object creation

The new class instance is created through a two-stage process, the __new__ method creates a new instance, and __init__ initializes the instance. The user is already familiar with the definition of the __init__ method, but the user rarely defines the __new__ method, but it is also possible to customize the creation of class instances.
Special methods for property access

We can customize property access for class instances by implementing the following methods.

Class Account (object): num_accounts = 0  def __init__ (self, Name, balance): = name  self.balance = ba Lance  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.balanc E = Self.balance + amt  def withdraw (self, AMT):  self.balance = Self.balance-amt  def inquiry (self):  Return "name={}, balance={}". Format (, 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 if the name is not an instance property and cannot be found in the object's class inheritance chain. This method should return a property value or throw a Attributeerror exception. For example, if X is an instance of the account class, attempting to access a property that does not exist will call this method.

>>> acct = Account ("Obi", ten) >>> acct.numberhey I dont see any attribute called number

Note If __getattr__ references an instance property that does not exist, a dead loop may occur because the __getattr__ method is constantly being called.

2.__setattr__ (self, name, value) __: This method is called when a property assignment occurs. __SETATTR__ will insert the value into the instance property dictionary instead of using because it will cause a recursive invocation of the dead loop.

3.__delattr__ (self, name) __:del obj occurs when called.

4.__getattribute__ (self, name) __: This method is always called to implement property access for class instances.
Special methods for type simulation

For some types, Python defines certain syntax, for example, the elements of lists and tuples can be accessed by means of an indexed notation, and values can be additive by the + operator. We can create our own classes that use these special syntaxes, and the Python interpreter will invoke the methods we implement when it encounters these special syntaxes. Let's use a simple example below to illustrate this feature, which simulates the basic use of a Python list.

Class Customlist (object): Def __init__ (self, Container=none): # The class was just a wrapper around another list to # IL Lustrate Special methods If container is None:self.container = [] Else:self.container = Container def __len__ (sel f): # Called when a user calls Len (customlist instance) return Len (Self.container) def __getitem__ (self, Index): # cal LED when a user uses square brackets for indexing return Self.container[index] def __setitem__ (self, Index, value): # C    alled 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 ' on ' 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 + Ntainer)

Above, Customlist is a simple wrapper for a real list. We implemented some custom methods for the demonstration:

__len__ (self): 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): provides bracket index usage support 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): Called when assigning a value to Self[key on a Customlist class 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 when member is instrumented. Returns True if the item is included, otherwise false.

>>> myList = customlist () >>> mylist.append (1) >>> mylist.append (2) >>> Mylist.append (3) >>> Mylist.append (4) >>> 4 in Mylisttrue

5.__repr__ (self): Called when the Self is printed with print, 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): Called when the + operator is used to calculate the addition of two customlist instances.

>>> myList = customlist () >>> otherlist = customlist () >>> otherlist.append (+) >>> 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 certain special class methods. You can view a complete list of these custom methods in a Python document. In the next tutorial, we will put special methods together to discuss and interpret the descriptor as an important feature that is widely used in Python object-oriented programming.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.