Fundamentals of Python - object oriented programming

python completely adopts the idea of object-oriented. It is a real object-oriented programming language and supports the basic operations of object-oriented, such as inheritance, polymorphism and encapsulation.
Everything in python is an object. python supports many programming paradigms, such as object-oriented, process oriented, functional programming and so on.

The difference between object-oriented and process oriented

  • Process oriented programming pays more attention to the "logical flow of the program", which is a kind of "executor" thinking, which is suitable for writing small-scale programs.
  • Object oriented programming pays more attention to the "relationship between objects in software". It is a kind of "designer" thinking, which is suitable for writing large-scale programs.
  • Object oriented way of thinking: in case of complex problems, first find nouns from the problem (process oriented is more about finding verbs), then determine which of these nouns can be used as classes, and then determine the relationship between classes according to the attributes and methods of the classes determined by the needs of the problem.

·Summary of object-oriented and process oriented:
They are both ways of thinking to solve problems and the way of code organization.
Process oriented can be used to solve simple problems.
Solving complex problems: object-oriented grasp is used in the macro, and process oriented is still used in the micro processing.

Class definition


We define the attributes (data) and methods (behavior) of data types through classes, that is, "classes package behavior and state together".
An object is a concrete entity of a class, which is generally called "an instance of a class".

When creating objects from a class, each object will share the behavior of the class (the methods defined in the class), but will have its own attribute value (not shared state). More specifically: "method code is shared, and attribute data is not shared".
In Python, "everything is an object". A class is also called a class object, and instances of a class are also called instance objects.

The syntax format of the definition class is as follows:

class name:
  class body

The key points are as follows:
1. The class name must conform to the rule of "identifier"; As a general rule, the first letter is capitalized, and the "Hump principle" is used for multiple words.
2. In the class body, we can define attributes and methods.
3. Attributes are used to describe data, and methods (i.e. functions) are used to describe the operations related to these data.

class student():
    def __init__(self, name, score):
        self.name = name
        self.score = score
    
    def print_score(self):
        print('name:{0} score:{1}'.format(self.name, self.score))

s1 = student('sherry',100)
s2 = student('lily',90)
s1.print_score()
s2.print_score()

Output:
name:sherry score:100
name:lily score:90

__ init__ Construction method and__ new__ method

Further, a Python object contains the following parts:

1.id (identity identification code)
2. type (object type)
3. value (value of object)
(1) attribute
(2) method

To create an object, we need to define the constructor * * init() * * method. The construction method is used to perform "initialization of instance object", that is, after the object is created, initialize the relevant properties of the current object without return value.

The key points of init() are as follows:
1. The name is fixed and must be: init(). The first parameter is fixed and must be: self. Self refers to the instance object just created.
2. Constructors are usually used to initialize instance properties of instance objects
3. Call the constructor through "class name (parameter list)". After calling, the created object is returned to the corresponding variable
4.init() method: initialize the created object. Initialization refers to "assign value to instance attribute"
5.new() method: used to create objects, but we generally do not need to redefine this method.
6. If we don't define__ init__ Method, the system will provide a default__ init__ method. If we define a parameter__ init__ Method, the system does not create a default__ init__ method.

Note: 1 Self in Python is equivalent to the self pointer in C + +, and the this keyword in JAVA and C #. In Python, self must be the first parameter of the constructor, and the name can be modified arbitrarily. But generally follow the Convention, which is called self.

Instance properties and instance methods

Instance properties

Instance properties are properties that are subordinate to instance objects:
1. Instance properties are generally__ init()__ Defined in
2. In other instance methods of this class, it is also through self Access by property name
3. After the instance object is created, access: obj Attribute name

Example method

Instance methods are methods that are subordinate to instance objects,
The definition format of the instance method is as follows:

def method name (self [, parameter list]):
  function body

The format of calling method is as follows:

obj. Method name ([parameter list])

main points:
1. When defining an instance method, the first parameter must be self. As before, self refers to the current instance object. 2. When calling an instance method, you do not need or cannot pass parameters to self. Self is automatically passed by the interpreter.

Differences between functions and methods

  1. Are used to complete a function of the statement block, the essence is the same.
  2. When a method is called, it is called through an object. Method is subordinate to a specific instance object, which is not characteristic of ordinary functions.
  3. Intuitively, self needs to be passed when defining methods, but not functions.

Method call essence of instance object

class student():
    def __init__(self, name, score):
        self.name = name
        self.score = score
    
    def print_score(self):
        print('name:{0} score:{1}'.format(self.name, self.score))

s1 = student('sherry',100)
s1.print_score()
student.print_score(s1)

Output:
name:sherry score:100
name:sherry score:100

Other operations

  1. dir(obj) can obtain all attributes and methods of the object
  2. obj. Attribute dictionary of dict object
class student():
    def __init__(self, name, score):
        self.name = name
        self.score = score
    
    def print_score(self):
        print('name:{0} score:{1}'.format(self.name, self.score))

s1 = student('sherry',100)
print(dir(s1))		#s1 all properties and methods of the object
print(s1.__dict__). #Attribute dictionary of student object

Output:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'print_score', 'score']
{'name': 'sherry', 'score': 100}
  1. pass empty statement
  2. isinstance (object, type) determines whether the "object" is a "specified type"

Class object

In the class definition format, "class name:". In fact, when the interpreter executes a class statement, it creates a class object, also known as a type object.

class student():
    def __init__(self, name, score):
        self.name = name
        self.score = score
    
    def print_score(self):
        print('name:{0} score:{1}'.format(self.name, self.score))

print(type(student))
print(id(student))

Output:
<class 'type'>
140442115598784

Class properties and class methods

Class properties

Class properties are properties that are subordinate to class objects, also known as class variables. Since class properties are subordinate to class objects, they can be shared by all instance objects.
Class attributes are defined as follows:

class Class name:
	Class variable name = Initial value

In or outside the class, we can read and write through: "class name. Class variable name".

class student():
    school = 'ucas'
    count = 0. # Class variable is used to count how many students have been initialized
    def __init__(self, name, score):
        self.name = name
        self.score = score
        student.count += 1 # Number of students + 1
    
    def print_score(self):
        print('school.{2} name:{0} score:{1}'.format(self.name, self.score,student.school))

s1 = student('sherry',100)
s1.print_score()
print(student.school)
print(student.count)

Output:
school.ucas name:sherry score:100
ucas
1

Class method

Class methods are methods subordinate to class objects. Class methods are defined by decorator @ classmethod. The format is as follows:

@classmethod
def class method name (cls [, parameter list])
  function body

main points:
1.@classmethod must be on the line above the method
2. The first cls must have; cls refers to the "class object" itself;
3. Calling class method format: "class name. Class method name (parameter list)". In the parameter list, you do not need or cannot pass values to cls.
4. Accessing instance properties and instance methods in class methods will lead to errors
5. When a subclass inherits the parent method, the cls passed in is a subclass object, not a parent object

# Test class method
class student():
    school = 'ucas'
    count = 0

    @classmethod
    def print_school(cls):
        print('school:{0}'.format(cls.school))

    def __init__(self, name, score):
        self.name = name
        self.score = score
        student.count += 1
    
    def print_score(self):
        print('school.{2} name:{0} score:{1}'.format(self.name, self.score,student.school))

student.print_school()

Output:
school:ucas

Static method

python allows you to define methods that are independent of "class objects", which are called "static methods".
”Static methods "are no different from ordinary functions defined in the module, except that" static methods "are placed in the" class namespace "and need to be called through the" class ".
Static methods are defined by the decorator @ staticmethod. The format is as follows:

@staticmethod
def static method name ([formal parameter list]):
  function body

main points:
1.@staticmethod must be on the line above the method
2. Call static method format: "class name. Static method name (parameter list)".
3. Accessing instance properties and instance methods in static methods will lead to errors

# Test static method
class student():
    school = 'ucas'
    count = 0

    @classmethod
    def print_school(cls):
        print('school:{0}'.format(cls.school))
    
    @staticmethod
    def add(a,b):
        print(a+b)

    def __init__(self, name, score):
        self.name = name
        self.score = score
        student.count += 1
    
    def print_score(self):
        print('school.{2} name:{0} score:{1}'.format(self.name, self.score,student.school))

student.add(100,200)

Output:
300

del() method (destructor) and garbage collection mechanism

  • __ del__ This method is called "destruct method", which is used to realize the operations required when the object is destroyed, such as releasing the resources occupied by the object, such as open file resources, network connection, etc.
  • Automatic garbage collection is implemented in python. When the object is not referenced (the reference count is 0), it is called by the garbage collector__ del__ method.
  • We can also delete the object with del statement to ensure the call__ del__ method.
    The system will automatically provide__ del__ Method. Generally, there is no need to customize the destructor method.
# Test deconstruction method
class person():
    def __del__(self):
        print('Destroy object')

p1 = person()
p2 = person()
del p1
print('over')

Output:
Destroy object
over
 Destroy object

call() method and callable object

Defined__ call__ The object of the method is called "callable object", that is, the object can be called like a function.

# Test callable methods
class caculate():
    def __call__(self,a,b):
        print(a+b)

cacul = caculate()
cacul(10,20)

Output:
30

Keywords: Python Back-end

Added by 2paulm on Sat, 12 Feb 2022 01:55:55 +0200