Learning Python: Classes and instances

Author: Mysterious Soul Studio – Hot ants


Class, in the study we can put the object-oriented classes as a specification, this idea is my personal experience, the feeling is very important, in addition to the function of packaging, such as a specification, our own specifications can be customized, from this perspective, in the future we learn design patterns, the understanding of design patterns can be helpful. Second, classes in the language are abstract templates that describe collections of objects with the same properties and methods, such as the Animal class. Instances are concrete “objects” created from classes, each of which has the same methods but may have different data.

Python uses the class keyword to define classes. The basic structure is as follows:

classThe name of the class(List of parent classes):
    pass
Copy the code

Class names are often named in a camel’s back, trying to make their literal meaning reflect the purpose of the class. Python uses multiple inheritance. A class can inherit from more than one parent class (also known as a base class or a superclass). The inherited base classes are listed in parentheses after the class name. The list of inherited parent classes can be empty, in which case the parentheses can be omitted. But in Python3, even if you define a class using a method like classStudent:pass that does not explicitly inherit from any parent class, it inherits from the object class by default. Object is the base class for all classes in Python3.

Here is a student class:

class Student:
    classroom = '101'
    address = 'beijing' 

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def print_age(self):
        print('%s: %s' % (self.name, self.age))
Copy the code

You can create an instance of a class by calling its instantiation method (also called an initializer or constructor in some languages). By default, an instance of a class can be generated using something like obj=Student(). However, each instance of a class usually has its own instance variables, such as name and age in this case. To reflect instance differences when instantiating, Python provides a def__init__(self): instantiation mechanism. In any class, a method named __init__ is the class’s instantiation method. Classes with an __init__ method are automatically called when instantiated, passing the corresponding arguments. Such as:

class Student:
li = Student("Bill", 24)
zhang = Student("Zhang"23),Copy the code

Instance variables and class variables

Instance variables:

Instance variables are variables owned by the instance itself. The variables of each instance are different in memory. Name and age in the __init__ method of the Student class are instance variables. Call an instance variable by dotting the instance name.

If we print the following four variables, we can see that each instance has the same variable name, but they hold independent values:

print(li.name)
print(li.age)
print(zhang.name)
print(Zhang.age) ------------------------ Li Si 24 Zhang SAN 23Copy the code

Class variables:

Variables defined outside of a method in a class are called class variables. Class variables are common to all instances and can be accessed and modified by each instance. In the Student class, the classroom and address variables are class variables. Class variables can be accessed by dotting the class name or instance name, for example:

Student.classroom
Student.address
li.classroom
zhang.address
Copy the code

When using instance variables and class variables, it must be noted that when accessing variables like Zhang. name, the instance will first look for the instance variable in its own variable list, if not, then it will look for the class variable list, if not, a pop-up exception.

The dynamic nature of the Python language allows you to add new instance variables to instances and new class variables and methods to classes at any time. So, li.classroom = ‘102’, either reassign the existing instance variable classroom, or create a new li-specific instance variable classroom and assign it to ‘102’. Look at the following example

>>> class Student:              The body of the class definition
    classroom = '101'           # class variables
    address = 'beijing'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def print_age(self):
        print('%s: %s' % (self.name, self.age))

>>> li = Student("Bill"24),Create an instance
>>> zhang = Student("Zhang"23),Create a second instance
>>> li.classroom # Li doesn't have the classroom instance variable itself, so look for the class variable, and it finds it!
'101'
>>> zhang.classroom # The same as li
'101'
>>> Student.classroom   Access class variables by class name
'101'
>>> li.classroom = '102'    # Crucial step! You actually created a unique instance variable for Li, named classroom, just like the class variable.
>>> li.classroom    Next time you access li's instance variable classroom
'102'
>>> zhang.classroom # zhang does not have the instance variable classroom, but still calls the class variable classroom
'101'
>>> Student.classroom   # Stay the same
'101'
>>> del li.classroom    Remove li instance variable classroom
>>> li.classroom        # Everything is back to normal
'101'
>>> zhang.classroom
'101'
>>> Student.classroom
'101'
Copy the code

Class methods:

Python classes contain instance methods, static methods, and class methods. These methods are classed either in code choreography or in memory, depending on the parameters passed in and how they are called. Inside the class, use the def keyword to define a method.

Instance methods

Class instance methods are called by the instance and contain at least one argument, self, as the first. When an instance method is executed, the instance calling the method is automatically assigned to self. Self represents an instance of the class, not the class itself. Self is not a keyword, but a common name by Python convention. You can call yourself something else, but it’s not recommended.

For example, print_age() in our previous Student class is the instance method:

def print_age(self):
        print('%s: %s' % (self.name, self.age))

# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
# call method
li.print_age()
zhang.print_age()
Copy the code

A static method

Static methods are called by the class and have no default arguments. Remove self from the instance method argument and add @staticmethod above the method definition to make it a staticmethod. It is a class, independent of the instance. It is recommended to use only the class name. How static methods are called. (Although instance names can also be used. Static method calls)

class Foo:

    @staticmethod
    def static_method():
        pass

# call method
Foo.static_method()
Copy the code

Class method

Class methods are called by the class, decorated with @classMethod, and passed at least one CLS argument (representing the class itself, like self). When a class method is executed, the class calling the method is automatically assigned to the CLS. It is recommended to use only the class name. How a class method is called. (Although instance names can also be used. Class method.)

class Foo:

    @classmethod
    def class_method(cls):
        pass

Foo.class_method()
Copy the code

Look at a comprehensive example:

class Foo: 

    def __init__(self, name):
        self.name = name 

    def ord_func(self):
        """Define instance method with at least one self argument."""
        print('Instance method')

    @classmethod
    def class_func(cls):
        """Define a class method with at least one CLS parameter."""
        print('Class method')

    @staticmethod
    def static_func():
        """Define static methods with no default parameters"""
        print('Static method') 
Copy the code
Call the instance method
f = Foo("Jack")
f.ord_func()
Foo.ord_func(f) # Note that this method of calling, while feasible, is not recommended!

Call the class method
Foo.class_func()
f.class_func()  # Note that this method of calling, while feasible, is not recommended!

Call static methods
Foo.static_func()
f.static_func() # Note that this method of calling, while feasible, is not recommended!
Copy the code

How are classes, class methods, class variables, instances of classes, and instance variables held in memory?

There is only one copy of a class, all of its methods, and class variables in memory, shared by all instances. Each instance holds itself and its instance variables independently in memory.

When an instance is created, in addition to encapsulating instance variables such as name and age, it also holds a class object pointer that points to the address of the class to which the instance belongs. Thus, instances can find their own classes and make related calls, whereas classes cannot find an instance of themselves.

Inheritance of Python classes

In ptyhon, a class can inherit from multiple classes at the same time.

Class The name of the class (superclass 1, superclass 2...) The class bodyCopy the code

Python class inheritance is depth-first

Python supports multiple inheritance, but the order of multiple inheritance look-ups is different for classic and new classes.

Classic class:

class P1: 
     def foo(self):           
         print 'p1-foo' 

class P2 : 
     def foo(self): 
         print 'p2-foo' 

     def bar(self): 
         print 'p2-bar' 

class C1 (P1,P2): 
     pass  

class C2 (P1,P2): 
     def bar(self): 
         print 'C2-bar'   

class D(C1,C2): 
     pass 
Copy the code

Instance D calls foo() in the search order d => C1 => P1

Instance D calls bar() in the search order d => C1 => P1 => P2

In other words, a classic class searches for attributes in a left-to-right, depth-first fashion. D first looks to see if it has a method in foo. If it does not, d looks to see if it has a method in C1, the nearest parent. If it does not, d continues to look up until it finds a method in P1.

Python class inheritance is breadth-first

The new class:

class P1(object): 
     def foo(self):           
         print 'p1-foo' 

class P2(object):
     def foo(self): 
         print 'p2-foo' 

     def bar(self): 
         print 'p2-bar' 

class C1 (P1,P2): 
     pass  

class C2 (P1,P2): 
     def bar(self): 
         print 'C2-bar'   

class D(C1,C2): 
     pass 
Copy the code

Example D calls foo() in the search order d => C1 => C2 => P1 Instance D calls bar() in the search order d => C1 => C2 you can see that the new class uses the breadth-first approach to search for attributes.

This article was first published on the Wechat subscription account of Dark Soul Studio

For more, subscribe to “Python”.

Python source code learning Notes (1) compilation and installation

Python hacker related electronic resources and book recommendations

4.1 Data capture with the Sniffer