Python-like classes and instances

Source: Internet
Author: User
Tags instance method

0x00 Preface

class , in learning object-oriented We can regard the class as a specification, the idea of my personal experience, the feeling is very important, in addition to the function of encapsulation, class as a specification, we can customize the specification, from this point of view, in the future when we learn design patterns, The understanding of design patterns can be very helpful. Second, a class in a language is an abstract template used to describe a collection of objects with the same properties and methods, such as the animal class. An instance is a specific "object" created from a class, each of which has the same method, but the data may be different.

Python uses the class keyword to define a class with the following basic structure:

class Class name (parent class list):     Pass

The class name usually uses the hump-style naming method, as far as possible to let the literal meaning reflect the function of the class. Python uses a multi-inheritance mechanism in which a class can inherit multiple parent classes (also called base classes, superclass), and the inherited base classes are in sequence, written in parentheses after the class name. The inherited parent class list can be empty, and parentheses can be omitted at this time. But in Python3, even if you adopt a method like Classstudent:pass that does not explicitly inherit any parent class defined by a class, it also inherits the object class by default. Because, object is the base class for all classes in Python3.

Here is a student class:

class Student:     ' 101 ' ' Beijing'           def __init__ (self, Name, age):         = name                     = Age def print_age (self): print ( ' %s:%s ' % (Self.name, self.age))

You can create an instance of a class by invoking the instantiation method of the class, which is also called an initialization method or constructor in some languages. By default, an instance of a class can be generated using a method like Obj=student (). However, typically every instance of a class has its own instance variable, such as name and age here, and in order to represent the different instances when instantiated, Python provides a def__init__ (self): instantiation mechanism. In any class, the method named __init__ is the instantiation method of the class, and the class with the __init__ method automatically calls the method when it is instantiated and passes the corresponding parameter. Like what:

Class= Student (" John Doe ",= Student (" Zhang San " , 23)

0x01 instance variables and class variables instance Variable

An instance variable refers to a variable owned by the instance itself. The variables for each instance are not the same in memory. The name and age of the __init__ method in the student class are two instance variables. An instance variable is called by the instance name plus a dot.

We print the following four variables, and we can see that the variable names of each instance are the same, but the values they hold are separate:

Print (Li.name) Print (li.age) Print (Zhang.name) Print (zhang.age)------------------------ John Doe Zhang San 23

class Variables

A variable defined in a class, other than a method, is called a class variable. A class variable is a variable that is public to all instances, and each instance can access and modify a class variable. In the student class, the classroom and address two variables are class variables. Class variables can be accessed by the name of the class or by the dot of the instance name, such as:

Student.classroomStudent.addressli.classroomzhang.address

When using instance variables and class variables, it is important to note that when using a similar zhang.name access variable, the instance will first look in its own instance variable list to see if there is an instance variable, if not, then it will go to the class variable listing, if not, pop the exception.

Python's dynamic language features allow us to add new instance variables to the instance at any time, adding new class variables and methods to the class. Therefore, when using Li.classroom = ' 102 ', either to reassign the existing instance variable classroom, or to create a new Li-specific instance variable classroom and assign a value of ' 102 '. Look at the following example

>>>classStudent:#the definition body of a classClassroom ='101'           #class VariablesAddress ='Beijing'    def __init__(self, Name, age): Self.name=name Self.age= Agedefprint_age (self):Print('%s:%s'%(Self.name, self.age))>>> li = Student ("John Doe", 24)#Create an instance>>> Zhang = Student ("Zhang San", 23)#Create a second instance>>> Li.classroom#Li does not have a classroom instance variable, so go for the class variable, and it finds it! '101'>>> Zhang.classroom#Same with Li'101'>>> Student.classroom#Accessing class variables by class name'101'>>> Li.classroom ='102'    #a key step! The fact is that the unique instance variable is created for Li, except that the name and the class variable are called classroom. >>> Li.classroom#once again, access to the Li own instance variable classroom'102'>>> Zhang.classroom#Zhang does not have an instance variable classroom and still accesses the class variable classroom'101'>>> Student.classroom#remain the same'101'>>>delLi.classroom#An instance variable of Li was removed classroom>>> Li.classroom#everything has been restored.'101'>>>Zhang.classroom'101'>>>Student.classroom'101'

methods of the 0x03 class

The Python class contains three methods of instance methods, static methods, and class methods. These methods, whether in code orchestration or in memory, belong to the class, except that the parameters passed in and the method of invocation are different. Within the class, use the DEF keyword to define a method.

instance Method

An instance method of a class is called by an instance, contains at least one self parameter, and is the first argument. When you execute an instance method, the instance that invokes the method is automatically assigned to self. Self represents an instance of a class, not the class itself. Self is not a keyword, but a python contract named idiomatic, you can definitely take another name, but it is not recommended.

For example, the Print_age () in the student class before us is an instance method:

def print_age (self):         Print ('%s:%s' % (self.name, self.age)) #  -------------------------- # Calling Methods li.print_age () zhang.print_age ( )

Static Methods

Static methods are called by the class without default parameters. By removing self from the instance method parameter and then adding @staticmethod above the method definition, it becomes a static method. It belongs to a class, and is independent of the instance. It is recommended to use only the class name. static method invocation. (Although you can also use the instance name. Method invocation of static methods)

class Foo:    @staticmethod    def  Static_method ():        pass# Call method Foo.static_method ()

class Method

Class methods are called by the class and are decorated with @classmethod at least one CLS (The surrogate class itself, like the self) parameter. When you execute a class method, the class that invokes the method is automatically assigned the value to the CLS. It is recommended to use only the class name. The method of calling the class. (Although you can also use the instance name. Method invocation of class methods)

class Foo:    @classmethod    def  Class_method (CLS):        passFoo.class_ Method ()

See a comprehensive example:

classFoo:def __init__(self, name): Self.name=namedefOrd_func (self):"""define an instance method with at least one self parameter"""        Print('instance Method') @classmethoddefClass_func (CLS):"""define a class method with at least one CLS parameter"""        Print('class Method') @staticmethoddefStatic_func ():"""define static methods with no default parameters"""        Print('Static Methods') #Invoking instance methodsf = Foo ("Jack") F.ord_func () Foo.ord_func (f)#Please note that this method of invocation, although feasible, but not recommended! #Calling class methodsFoo.class_func () f.class_func ( )#Please note that this method of invocation, although feasible, but not recommended! #calling a static methodFoo.static_func () f.static_func ( )#Please note that this method of invocation, although feasible, but not recommended! 

how the 0x04 class, the method of the class, the class variable, the instance of the class, and the instance variable are saved in memory

Classes, all methods of a class, and class variables have only one copy in memory, and all instances share them. Each instance stores itself and its own instance variables independently in memory.

When you create an instance, in addition to enclosing an instance variable such as name and age, the instance holds a pointer to a class object that points to the address of the class to which the instance belongs. Thus, the instance can find its own class and make related calls, and the class cannot find an instance of itself.

0x05 Inheritance of Python classes

In Ptyhon Class A class can inherit multiple classes at the same time, syntax:

class Class Name (parent Class 1, parent Class 2,...) Class Body

Python class inheritance Depth first

Python supports multiple inheritance, but the order of multiple-inheritance lookups is different for classic and modern classes.

Classic class:

classP1:deffoo (self):Print 'P1-foo' classP2:deffoo (self):Print 'P2-foo'      defBar (self):Print 'P2-bar' classC1 (P1,P2):Pass  classC2 (P1,P2):defBar (self):Print 'C2-bar'   classD (C1,C2):Pass 

When instance D calls Foo (), the search order is d = = C1 = P1

When instance D calls bar (), the search order is d = C1 = P1 = P2

In other words, the classic class searches for attributes in the "left-to-right, depth-first" way. D First look for whether it has the Foo method, no find the nearest parent class C1 the method, if not, continue to look up until the method is found in P1, find the end.

Python class inherits the breadth first

New class:

classP1 (object):deffoo (self):Print 'P1-foo' classP2 (object):deffoo (self):Print 'P2-foo'      defBar (self):Print 'P2-bar' classC1 (P1,P2):Pass  classC2 (P1,P2):defBar (self):Print 'C2-bar'   classD (C1,C2):Pass 

When instance D calls Foo (), the search order is d = C1 = C2 = P1
When instance D calls bar (), the search order is d = = C1 = C2
As you can see, the search method for the new class is to look for attributes in a "breadth-first" way.

Reference

Python-like classes and instances

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: info-contact@alibabacloud.com 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.