Python is object-oriented, let’s meet it for a while

 Event address: CSDN 21-day learning challenge


Preface

The most commonly mentioned in computer programming are classes and objects. Mastering classes and objects will help you quickly implement complex projects using the Python programming language.


1. What is object-oriented?

In real life, people's thinking is abstract, and we abstract the things we encounter. At this time, the type of object—class—appears. First define the class, then the class creates the object, and finally the object manages the program. Just like human thinking, abstract first, then instantiate, and finally execute. Object-oriented programming is a process of constantly abstracting data and methods.

2. What is an object?

Everything is an object. Everyone and things we can see and touch in the real world are objects, such as people, cats, dogs, cars, etc. In the computer world, we use virtual programming codes to abstract things in the real world into objects, and then use object-oriented programming ideas to solve various problems in the real world. When people understand the world, they simply process objects into two parts- attributes and behaviors.

Objects have properties , which can be called states or variables. Just as each factory has attributes such as name, location, area, and products, we can use these data to describe the attributes of the object.

Example: Properties of the object "Factory"

Objects have behaviors , which can also be called methods, just like every factory has to do: inspection, assembly, packaging, and shipping. Object-oriented programming defines code blocks that complete a certain function as methods. Methods can be called by other programs or by the object itself.

Example: Behavior of the object "Factory"

 3. Important terminology of object-oriented

  • Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection.
  • Class attributes: Class attributes are common throughout the instantiated object. Class variables are defined in the class and outside the function body, and are usually not used as instance variables.
  • Method rewriting: If the method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called method overwriting, also known as method rewriting.
  • Instance attributes: defined in methods, only affect the current instance of the class.
  • Encapsulation: Encapsulate functions or functions that need to be reused so that other programs can call them directly.
  • Inheritance: refers to a derived class inheriting the fields and methods of a base class. Inheritance also allows an object of a derived class to be treated as an object of a base class.
  • Polymorphism: A function has multiple forms of expression, and calling a method has multiple forms, but the methods of expression are different.
  • Instantiation: Create an instance of a class, a specific object of the class.
  • Method: Function defined in the class.
  • Object: An instance of a data structure defined by a class. Objects include two data members (class variables and instance variables) and methods.

 4. Class syntax

A class must be defined before it can be used. To define a class is to define a template for this type of object and define its properties and methods. Python provides the class keyword to declare a class, which has member attributes and member methods. The definition format of a class in Python is as follows:

class  [类名]:
    [语法块]

3 elements that define a class:

  1. Class name: The name of this type of thing, satisfying the camel case naming method (Note: the first letter of each word is capitalized)
  2. Properties: What characteristics does this type of thing have?
  3. Method: What kind of behavior does this type of thing have?

Define a class:

need:

Factory inspection area, factory assembly area, factory packaging area, factory shipping area

analyze:

Define a factory class

Define 4 methods: inspection, assembly, packaging, and shipping

According to requirements, no attributes need to be defined

class Factory:
    '''这是一个工厂类'''

    def jianyan(self):
        print('这是工厂里面负责检验的。')

    def zuzhuang(self):
        print('这是工厂里面负责组装的。')

    def baozhuang(self):
        print('这是工厂里面负责包装的。')

    def chuhuo(self):
        print('这是工厂里面负责出货的。')

factory1=Factory()
factory1.jianyan()
factory1.zuzhuang()
factory1.baozhuang()
factory1.chuhuo()

#下面是输出
'''
这是工厂里面负责检验的。
这是工厂里面负责组装的。
这是工厂里面负责包装的。
这是工厂里面负责出货的。
'''

5. The self parameter in the method

The method is called by which object, the self in the method is  the reference of that object

  • Within the method encapsulated by the class, self  represents  the object itself that is currently calling the method.
  • When calling a method , there is no need to pass the self parameter
  • Inside the method, access the properties of the object through self.
  • Outside the class, access the properties and methods of the object through the instance name.

6. Methods in the format of __method name__

This format method is a built-in method provided by Python and is described as follows:

method name type effect
__new__ method It will be called automatically when creating an object . Used to control the process of generating a new instance, it is a class-level method. There must be at least one parameter cls, representing the class to be instantiated. The call to the __new__ method occurs before __init__ .
__init__ method It will be called automatically when the object is initialized . Used to initialize a new instance and control the initialization process, such as adding some attributes and performing some additional operations, which occur after the class instance is created. It is an instance level method.
__of the__ method It will be called automatically before the object is destroyed from memory .
__str__ method Returns the description information of the object and uses the print function output. When using print to output an object, as long as you define the __str__ method, the data returned from this method will be printed.

__str__The method needs to return a string as a description of this object.

7. Initialization method (__init__) 

When an object is created using classname() , the following actions are automatically performed:

  • Allocate space in memory for the object - create the object
  • Set initial values ​​for the properties of the object - initialization method (__init__)

This initialization method is the __init__ method, which is a built-in method of the object. 

The __init__ method is a method specifically used to define what attributes a class has.

Example:

Add the __init__ method to the Factory and verify that this method will be automatically called when creating the object.

class Factory:
    '''这是一个工厂类'''
    
    def __init__(self):
        print('这是一个初始化方法,创建对象时,会被自动调用!')

factory1=Factory()
#输出:
'''
这是一个初始化方法,创建对象时,会被自动调用!

'''

8. Define attributes inside the initialization method (__init__)

  Attributes can be defined __init__using   self.attribute name = initial value of the attribute inside  the method.

After defining the attribute, if you create an object using the Cat class, you will have this attribute.

class Factory:
    '''这是一个工厂类'''
    
    def __init__(self):
        print('这是一个初始化方法,创建对象时,会被自动调用!')
        #self.属性名=属性的初始值
        self.name='X工厂'

    def jianyan(self):
        print('这是工厂里面负责检验的。')

#使用类名()创建对象时,会自动调用初始化方法__init__
factory1=Factory()
factory1.jianyan()
print(factory1.name)
#输出:
'''
这是一个初始化方法,创建对象时,会被自动调用!
这是工厂里面负责检验的。
X工厂

'''

9. Transform initialization method (__init__) - set initial value while initializing 

 During the development process, if you want to  set the properties of the object while creating the object , you can  modify __init__the method .

  • Define the attribute value you want to set as  __init__a parameter of the method
  • Used inside methods to  receive externally passed parameters self.属性 =形参
  • When creating an object, use 类名(属性1,属性2,……)
class Factory:
    '''这是一个工厂类'''
    
    def __init__(self,facroty_name):
        print('这是一个初始化方法,创建对象时,会被自动调用!')
        #self.属性名=属性的初始值
        self.name=facroty_name

    def jianyan(self):
        print('这是工厂里面负责检验的。')

#使用类名()创建对象时,会自动调用初始化方法__init__
factory1=Factory('万向集团')
factory1.jianyan()
print(factory1.name)
#输出:
'''
这是一个初始化方法,创建对象时,会被自动调用!
这是工厂里面负责检验的。
万向集团
'''

10. __del__Method 

__del__Automatically call methods before an object is destroyed from memory 

Application scenarios:

__init__Method transformation initialization method can make object creation more flexible

__del__Method If you want to do something else before the object is destroyed, you can consider this method.

An object is created by calling classname() and the life cycle begins

Once the _ _del__ method of an object is called, the life cycle ends

During the object's life cycle, you can access object properties or let the object call methods.

class Factory:
    '''这是一个工厂类'''
    
    def __init__(self,facroty_name):
        #self.属性名=属性的初始值
        self.name=facroty_name
        print('{}。'.format(self.name))

    def jianyan(self):
        print('这是工厂里面负责检验的。')

    def __del__(self):
        print('{}工厂休假!'.format(self.name))


#使用类名()创建对象时,会自动调用初始化方法__init__
#factory1是一个全局变量
factory1=Factory('万向集团')
factory1.jianyan()
print(factory1.name)
#del关键字可以删除一个对象
del factory1


#输出:
'''
万向集团。
这是工厂里面负责检验的。
万向集团
万向集团工厂休假!

'''

11. __str__Method 

In Python, using print (object name), by default it will output:  which class the object referenced by  this variable is created by , and its address in memory (hexadecimal representation).

class Factory:
    '''这是一个工厂类'''

    def jianyan(self):
        print('这是工厂里面负责检验的。')

factory1=Factory()
print(factory1)

#输出:
'''
<__main__.Factory object at 0x00000235CE8053F0>

'''

If you can print custom content when using print output variables in development, you can use  __str__this built-in method.

Note:  __str__It must be a character when using the method

class Factory:
    '''这是一个工厂类'''

    def jianyan(self):
        print('这是工厂里面负责检验的。')

    def __str__(self):
        return '我是一个超级工厂!'

factory1=Factory()
print(factory1)

#输出:
'''
我是一个超级工厂!

'''

 12. Packaging

Encapsulate properties and methods into an abstract class, and the details of object methods are encapsulated inside the class.

class Factory:
    '''这是一个工厂类'''

    def jianyan(self):
        print('这是工厂里面负责检验的。')

    def zuzhuang(self):
        print('这是工厂里面负责组装的。')

    def baozhuang(self):
        print('这是工厂里面负责包装的。')

    def chuhuo(self):
        print('这是工厂里面负责出货的。')

factory1=Factory()
factory1.jianyan()
factory1.zuzhuang()
factory1.baozhuang()
factory1.chuhuo()

#下面是输出
'''
这是工厂里面负责检验的。
这是工厂里面负责组装的。
这是工厂里面负责包装的。
这是工厂里面负责出货的。
'''

 13. Private attributes

In actual work, we sometimes need to restrict instances from modifying attributes at will. In this case, private attributes are used. Defining a private property is as simple as starting the property name with two underscores.

class Factory:
    '''这是一个工厂类'''
    def __init__(self,name,money):
        self.name=name
        self.__money=money
        print('公司名字叫:{}'.format(self.name))
        print('公司有{} 资产。'.format(__money))

    def jianyan(self):
        print('这是工厂里面负责检验的。')


factory1=Factory('X超级工厂',99999999)
factory1.jianyan()

#输出:
'''
公司名字叫:X超级工厂
Traceback (most recent call last):
  File "G:\Python Project Center\面向对象学习.py", line 15, in <module>
    factory1=Factory('X超级工厂',99999999)
  File "G:\Python Project Center\面向对象学习.py", line 7, in __init__
    print('公司有{} 资产。'.format(__money))
NameError: name '_Factory__money' is not defined
'''

14. Private methods 

Private methods are the same as private properties. Private methods can only be called within the class and cannot be called directly by the instance.

class Factory:

    def __inf(self):
        print('超级工厂')
    def zuzhuang(self):
        print('这里负责组装')

factory1=Factory()
factory1.zuzhuang()
factory1.__inf()
#输出
'''

Traceback (most recent call last):
  File "G:\Python Project Center\面向对象学习.py", line 10, in <module>
    factory1.__inf()
AttributeError: 'Factory' object has no attribute '__inf'
这里负责组装

'''

 15. Inheritance

Inheritance is a concept of hierarchically dividing classes. The basic idea of ​​inheritance is to formulate a new class based on a class. This new class can not only inherit the attributes and methods of the original class, but also add new ones. properties and methods. The original class is called the parent class, and the new class is called the child class.

Inheritance: To achieve code reuse, the same code does not need to be written repeatedly.

Inherited syntax:

class 类名(父类名):
    pass

 The subclass inherits the parent class and can directly enjoy the methods encapsulated by the parent class without the need to develop again.

class Factory:
    def jianyan(self):
        print('这是工厂里面负责检验的。')

    def zuzhuang(self):
        print('这是工厂里面负责组装的。')

    def baozhuang(self):
        print('这是工厂里面负责包装的。')

    def chuhuo(self):
        print('这是工厂里面负责出货的。')


class QiCheFactory(Factory):
    def jinrong(self):
        print('这里提供金融服务!')

x_car=QiCheFactory()
x_car.chuhuo()
x_car.jinrong()

#输出:
'''
这是工厂里面负责出货的。
这里提供金融服务!

'''

 Things to note when inheriting:

1. In inheritance, if the subclass defines the __init__ method, the __init__ method of the parent class will not be automatically called and needs to be specifically called in the __init__ method of the subclass.

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

    def jianyan(self):
        print('这是{},里面负责检验的。'.format(self.name))

class QiCheFactory(Factory):
    def __init__(self):
        print('超级工厂!')

    def jinrong(self):
        print('这里提供金融服务!')

x_car=QiCheFactory()
x_car.jianyan()
#输出:
'''
Traceback (most recent call last):
  File "G:\Python Project Center\面向对象学习.py", line 16, in <module>
    x_car.jianyan()
  File "G:\Python Project Center\面向对象学习.py", line 6, in jianyan
    print('这是{},里面负责检验的。'.format(self.name))
AttributeError: 'QiCheFactory' object has no attribute 'name'
超级工厂!

'''

 We can call the __init__ method using the super function.

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

    def jianyan(self):
        print('这是{},里面负责检验的。'.format(self.name))

class QiCheFactory(Factory):
    def __init__(self):
        super(QiCheFactory,self).__init__('超级工厂')


    def jinrong(self):
        print('这里提供金融服务!')

x_car=QiCheFactory()
x_car.jianyan()
#输出:
'''
这是超级工厂,里面负责检验的。

'''

2. Subclasses cannot inherit the private methods of the parent class, nor can they call the private methods of the parent class.

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

    def jianyan(self):
        print('这是{},里面负责检验的。'.format(self.name))

    def __jianyan(self):
        print('这是{},里面负责检验重要物料。'.format('特殊车间'))

class QiCheFactory(Factory):
    def __init__(self):
        pass

    def jinrong(self):
        print('这里提供金融服务!')

x_car=QiCheFactory()
x_car.jianyan()
x_car.__jianyan()
#输出:
'''
Traceback (most recent call last):
  File "G:\Python Project Center\面向对象学习.py", line 21, in <module>
    x_car.__jianyan()
AttributeError: 'QiCheFactory' object has no attribute '__jianyan'. Did you mean: 'jianyan'?
这是超级工厂,里面负责检验的。

'''

16. Polymorphism

Different subclass objects call the same parent class method, resulting in different execution results:

  1. Polymorphism increases code flexibility
  2. Based on inheriting and overriding parent class methods
  3. It is a technique for calling methods and will not affect the internal design of the class.
class Factory:
    def shengchan(self):
        print('我们负责生产高铁。')

class QiCheFactory(Factory):
    def shengchan(self):
        print('我们负责生产汽车。')

class LunTaiFactory(Factory):
    def shengchan(self):
        print('我们负责生产轮胎。')

qiche=QiCheFactory()
qiche.shengchan()

luntai=LunTaiFactory()
luntai.shengchan()

#输出:
'''
我们负责生产汽车。
我们负责生产轮胎。

'''

 analyze:

        When the subclass and the parent class have the same method, the subclass method will override the parent class method, so that the code will always call the subclass method at runtime. This is polymorphism.

        Polymorphism means multiple forms. Polymorphism means that you can operate on an object even if you don't know what type the object it refers to is. Polymorphism exhibits different behaviors depending on the class.

To determine whether an instance is an object, you can use the isinstance function. Examples are as follows:

class Factory:
    def shengchan(self):
        print('我们负责生产高铁。')

class QiCheFactory(Factory):
    def shengchan(self):
        print('我们负责生产汽车。')

class LunTaiFactory(Factory):
    def shengchan(self):
        print('我们负责生产轮胎。')

qiche=QiCheFactory()
luntai=LunTaiFactory()

print(isinstance(qiche,QiCheFactory))
print(isinstance(qiche,Factory))
print(isinstance(luntai,LunTaiFactory))
print(isinstance(luntai,Factory))
#输出:
'''
True
True
True
True

'''

 17. Class variables

 Class variables can be used directly without instantiation, which is equivalent to being bound to the class instead of the instance.

class Factory:
    name='X工厂'

print(Factory.name)

#输出
'''

X工厂

'''

 But class variables can also be called in instances. It is worth noting that instances cannot modify class variables.

class Factory:
    name='X工厂'

print(Factory.name)

qiche=Factory()
luntai=Factory()

print(qiche.name)
print(luntai.name)

Factory.name='超级工厂'

print(qiche.name)
print(luntai.name)

#输出
'''

X工厂
X工厂
X工厂
超级工厂
超级工厂

'''

18. Static methods

       Static methods are somewhat similar to class variables. Static methods are already allocated and defined when the class is defined. Static methods do not bind classes or instances, which is equivalent to adding a prefix to the method. Defining static methods introduces a new concept - decorators.

The syntax for defining a static method is to add " @staticmethod "        to the line above the function definition (no blank lines) . Static methods no longer have the first default parameter self . Therefore, the static method itself cannot call member variables and member methods. Static methods do not need to be instantiated before use. They can be used directly like class variables. Others are no different from ordinary functions.

class Factory:
    name='X工厂'

    @staticmethod
    def inf():
        print('本公司是世界五百强!')

Factory.inf()
#输出
'''

本公司是世界五百强!

'''

19. Class methods 

Class method, as the name implies, is that the method is bound to the defined class, not to the instance.

Defining a class method is somewhat similar to a static method. It is to add a decorator " @classmethod " on the previous line (no blank line) before defining the class method . Unlike static methods, class methods and member methods have an initial parameter, but this parameter is different from member methods. The first parameter of the member method points to the instance, while the class method points to the defined class itself, so the class method can read and modify class variables.

class Factory:
    name='X工厂'

    @classmethod
    def inf(cls):
        print(cls.name,'世界五百强。')

Factory.inf()
#输出
'''

X工厂 世界五百强。

'''

Guess you like

Origin blog.csdn.net/weixin_44793743/article/details/126393846