Getting Started with Classes and Objects in Python

This article will talk about classes and objects in Python. Python is a language that has objects everywhere. If you have ever learned about Python, you should have heard that Python is an object-oriented programming language, so you may often read When it comes to "object-oriented" programming, the language of object-oriented programming will have three characteristics: encapsulation, inheritance, and polymorphism.

The operations of many functions and methods that we usually come into contact with have these properties. We only know how to use them, but have not yet deeply understood their essence. The following is an introduction to the relevant knowledge about classes and objects.
package

The concept of encapsulation should not be unfamiliar. For example, we encapsulate some data into a list, which belongs to data encapsulation. We can also encapsulate some code statements into a function for easy calling. This is the encapsulation of code. We can also encapsulate data and Code is packaged together. In terminology, properties and methods can be encapsulated to obtain objects.

First of all, we can define a class. This class has attributes and methods, but some partners will be more curious. Aren't the attributes and methods encapsulated into objects, why are they become classes again? For example, a class is like a rough house, and the object is a hardcover house transformed from the rough house.
 

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

A class object is created when the class definition is completed, which wraps the namespace created by the class definition. Class objects support two operations: property reference and instantiation.

The syntax for attribute references is the usual standard syntax: obj.name. For example, XiaoMing.height and XiaoMing.run are attribute references, the former will return a piece of data, while 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>

Assignment operations to class attributes are also supported here, 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 be regarded as the assignment of a class object as a parameterless function to a local variable, as follows:

In[6]:ming = XiaoMing()

ming is an instance object created by instantiating a class object, and 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]:小明在跑步

magic method __init__

The instantiation process of a class is not as simple as the above example. Generally, classes tend to create instance objects with an initial state, so a magic method of __init__ may be defined in the class. This method can Help receive and pass 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, see the following example.
 

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 in __init__(), and then the parameters x and y need to be received in print_coor. Next, by instantiating this class object, verify whether the parameters can be passed to the class through __init__() in the instantiation operation.

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

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

inherit

The so-called inheritance is that a new class is built 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 superclass, and the subclass will inherit Some properties and methods already in the parent class.

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

For example, in the above example, I did not define list_ as a list, but it can call the append method. The reason is that the class Mylist inherits from the base class list, and list_ is an instantiated object of Mylist, so list_ will also have the methods owned by the parent class list. Of course, the inheritance relationship between the two classes can be realized in the form of a custom class. We define two classes, Parent and Child. Child does not have any properties and methods, but inherits 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 of the parent class is defined in the subclass, the method or property corresponding to the parent class will be automatically overridden. Let’s use the above example to make it easier to understand.

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

You can see that there is a method in the subclass Child with the same name as the parent class Parent. When the subclass is instantiated and this method is called, the method in the subclass is finally called. Inheritance in Python also allows multiple inheritance, which means that a subclass can inherit attributes and methods from multiple parent classes, but this type of operation will cause code confusion, so it is not recommended in most cases, so I won't introduce it here. .


polymorphism

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

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

Both of the above classes have an introduce method. 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]:我是小红

     

Common BIFs

1、isssubclass(class,classinfo)

Determines whether a class is a subclass of another class, and returns True if it is, and False otherwise.

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

   

There are two points to note:

  • 1. The second parameter can not only pass in a class, but also pass in a tuple consisting of classes.
  • 2. A class is judged to be a subclass of itself, that is to say, when these two parameters are passed to the same class, True will also be returned.
    print(issubclass(Parent,Parent))
    '''
    True
    '''
    

    2、isinstance(object,classinfo)

    Determines whether an object is an instance object of a class, and returns True if it is, otherwise returns False.

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

    There are two points to note:

  • 1. The second parameter can not only pass in a class, but also pass in a tuple consisting of classes.
  • 2. If the first parameter passed in is not an object, it will always return False.

3、hasattr(object,name)

Determines whether an instance object contains an attribute, if so, returns True, otherwise returns False.

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324683675&siteId=291194637
Recommended