Comprehend Python's classes and objects in ten minutes, why don't you come to have a look?

First of all, Python is an object-oriented programming language, and object-oriented programming languages ​​have three major characteristics: encapsulation, inheritance, and polymorphism. So the key to learning Python is to master these points.

1. Package

Encapsulation is easy to understand. Simply put, it means encapsulating data into a list, which is data encapsulation.
Encapsulating a part of the code into a function is code encapsulation.
Then encapsulate the properties and methods to get the object.

First of all, we can define a class, and there are attributes and methods in this class.

class XiaoMing:
    #属性
    height = 180
    weight = 65
    sex = '男'
    #方法
    def run(self):
        print('小明在跑步')
    def sleep(self):
        print('小明在睡觉')

After the class is defined, a class object is created, and it is a wrapper for the namespace created by the class definition.

It is worth noting that the class object supports two operations: attribute reference and instantiation.

The syntax of attribute reference is the general standard syntax: obj.name. For example, XiaoMing.height and XiaoMing.run are attribute references, the former will return a piece of data, and the latter will return a method object.

In[1]:print(XiaoMing.height)
Out[1]:180

In[2]:print(XiaoMing.run)
Out[2]:<function XiaoMing.run at 0x0000021C6239D0D0>

Here also supports assignment operations on class attributes, such as assigning a new value to the weight attribute in the class.

In[3]:print(XiaoMing.weight)
Out[3]:65

In[4]:XiaoMing.weight = 100
In[5]:print(XiaoMing.weight)
Out[5]:100

The instantiation of a class can regard the class object as a parameterless function assignment to a local variable.
as follows:

In[6]:ming = XiaoMing()

Ming is an instance object created after the class object is instantiated. The properties and methods in the class can also be called through the instance object.

In[7]:ming.run()
Out[7]:小明在跑步

In[8]:print(xiaoming.height)
Out[8]:180
#通过向类对象调用方法返回的方法对象中传入实例对象也可以达到同样效果。
In[11]:XiaoMing.run(ming)
Out[11]:小明在跑步

__init__ method

But the general class is not so simple in the process of instantiation. In general, the class tends to create an instance object with an initial state.

Therefore, an __init__ method may be defined in the class to help receive and pass in parameters.
If a class defines the __init__ method, then the __init__ method will be automatically called for the newly created instantiated object during the instantiation of the class object,
such as:

class Coordinates:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def print_coor(self):
        print('当前坐标为(%s,%s)'%(self.x,self.y))

You can see that the parameters x and y are passed in __init__(), and then the parameters x and y need to be received in print_coor. You can instantiate this class object to verify whether the parameters can be passed to the class through __init__() Instancing operation.

In[9]:coor = Coordinates(5,3)
In[10]:coor.print_coor()

Out[10]:当前坐标为(5,3)

inherit

Inheritance is the construction of a new class on the basis of another class. This new class is called a subclass or a derived class, and the other class is called a parent class, a base class, or a super class, and the subclass inherits from the parent Some properties and methods already in the class. It's like a son inheriting his father's ability.

class Mylist(list):
    pass
list_ = Mylist()
list_.append(1)
print(list_)
'''
[1]
'''

For example, in this example, although list_ is not defined as a list, it can call the append method.
In fact, because the class Mylist inherits from the base class of list, and list_ is an instantiated object of Mylist, so list_ will also have methods owned by the parent class list.

Of course, we can also implement the inheritance relationship between the two classes in the form of a custom class. We define two classes, Parent and Child. There are no properties and methods in Child, but it is inherited from the parent class Parent.

class Parent:
    def par(self):
        print('父类方法')
class Child(Parent):
    pass
child = Child()
child.par()
'''
父类方法
'''

cover

When a method or property with the same name as that in the parent class is defined in a subclass, it will automatically override the method or property corresponding to the parent class, such as:

class Parent:
    def par(self):
        print('父类方法')
class Child(Parent):
    def par(self):
        print('子类方法')
child = Child()
child.par()
'''
子类方法
'''

You can see that there is one more method in the child class Child with the same name as the parent class Parent. When the child class is instantiated and this method is called, the method in the child class is finally called. Inheritance in Python also allows multiple inheritance, which means that a subclass can inherit the attributes and methods of multiple parent classes, but this type of operation will cause code confusion, so this method is generally not recommended.

Polymorphism

Polymorphism is relatively simple, such as defining two classes, these two classes have no relationship, but there are methods with the same name in the two classes, and when the instance objects of the two classes call this method respectively, the instance objects of different classes are called The method is also different.

class XiaoMing:
    def introduce(self):
        print("我是小明")
class XiaoHong:
    def introduce(self):
        print("我是小红")

There are introduce methods in the above two classes. We can instantiate the two classes and use the instance object to call this method to achieve polymorphism.

In[12]:ming = XiaoMing()
In[13]:hong = XiaoHong()

In[14]:ming.introduce()
Out[14]:我是小明

In[15]:hong.introduce()
Out[15]:我是小红

Commonly used BIF

1. issubclass(class,classinfo)
Determine whether a class is a subclass of another class, if it is, it returns True, otherwise it returns False.

class Parent:
    pass
class Child(Parent):
    pass
print(issubclass(Child,Parent))
'''
True
'''

Note:
① The second parameter can not only be passed into a class, but also a tuple composed of classes.
②A class is judged to be a subclass of itself, which means that when these two parameters are passed to the same class, it will also return True.

print(issubclass(Parent,Parent))
'''
True
'''

2. isinstance(object,classinfo)
Determine whether an object is an instance object of a class, if it is, it returns True, otherwise it returns False.

class Parent:
    pass
class Child:
    pass
p = Parent()
c = Child()
print(isinstance(p,Parent,Child))
#True
print(isinstance(c,Parent))
#False

Note:
① The second parameter can not only be passed into a class, but also a tuple composed of classes.
② If the first parameter is not an object, it will always return False.

3. hasattr(object,name)
Determine whether an instance object contains an attribute, if it is, it returns True, otherwise it returns False.

class Parent:
    height = 100
p = Parent()
print(hasattr(p,'height'))
'''
True
'''

It should be noted here that the second parameter name must be passed in as a string, if it is not, it will return False.

After understanding the relevant knowledge of these classes and objects like this, you can better understand the use of functions and methods. So it takes ten minutes to read to help understand the learning of Python classes and objects.

Then I still want to recommend the Python learning exchange group I built by myself : 645415122 , all of whom are learning Python, if you want to learn or are learning Python, you are welcome to join, everyone is a software development party, and you share it from time to time Dry goods (only related to Python software development), including a copy of the latest Python advanced materials and zero-based teaching compiled by myself in 2021. Welcome to the advanced and friends who are interested in Python to join!

**The following content is useless, this blog was crawled and used by search engines
(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶  ̄)(* ̄︶ ̄)(* ̄︶ ̄) What
is python? How long does it take to learn python? Why is it called crawler
python? Crawler rookie tutorial python crawler universal code python crawler how to make money
python basic tutorial web crawler python python crawler classic examples
python reptiles
(¯)¯ *) (* ¯)¯) (¯)¯ *) (* ¯)¯) (¯)¯ *) (* ¯)¯) ( ¯)¯) ( ¯)¯)
above The content is useless, this blog was crawled and used by search engines

Guess you like

Origin blog.csdn.net/pyjishu/article/details/115120811