Getting started with Python classes and objects

In this article, for classes and objects in Python, python language is everywhere. If you have a shallow understanding of python, you should have heard that Python is an object-oriented programming language, so you may often see passages like "Object-Oriented" programming, and object-oriented programming languages have three characteristics: encapsulation, inheritance and polymorphism.

The operations of many functions and methods we usually contact have these properties. We only know how to use them, but we haven't deeply understood its essence. Here are some knowledge about classes and objects.
encapsulation

The concept of encapsulation should not be unfamiliar. For example, we can 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 code encapsulation. We can also encapsulate data and code together. In terms, you can encapsulate properties and methods to get objects.

First, we can define a class. There are properties and methods in this class, but some partners will be curious. Properties and methods are encapsulated into objects. Why do they become classes again? For example, a class is like a blank room, and the object is a hardbound room transformed on the basis of the blank room.

class XiaoMing:
    #attribute
    height = 180
    weight = 65
    sex = 'male'
    #method
    def run(self):
        print('Xiao Ming is running')
    def sleep(self):
        print('Xiao Ming is sleeping')

When the class definition is completed, a class object is created, which wraps the namespace created by the class definition. Class objects support 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 is a property reference. 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>

It also supports the assignment of class attributes, such as giving 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 treat the class object as a parameterless function assigned to a local variable, as follows:

In[6]:ming = XiaoMing()

ming is an instance object created after instantiation of a class object. Properties and methods in the class can also be called through the instance object.

In[7]:ming.run()
Out[7]:Xiao Ming is running

In[8]:print(xiaoming.height)
Out[8]:180
#The same effect can be achieved by passing an instance object into the method object returned by calling the method on the class object
In[11]:XiaoMing.run(ming)
Out[11]:Xiao Ming is running

Magic method__ init__

Class instantiation is not always as simple as the above examples. Generally, classes tend to create instance objects with initial states, so one may be defined in the class__ init__ This method can help receive and pass in parameters.

And if a class is defined__ init__ Method, it will be automatically called for the newly created instantiated object during the instantiation of the class object__ init__ Method, see the following example.

class Coordinates:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def print_coor(self):
        print('Current coordinates are(%s,%s)'%(self.x,self.y))

You can see in__ init__ () passed in the parameters x and y, and then in print_coor needs to receive parameters x and Y. next, instantiate this class object to verify whether the parameters can pass__ init__ () is passed to the instantiation operation of the class.

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

Out[10]:Current coordinates are(5,3)

inherit

Inheritance is a new class built on the basis of another class. This new class is called a subclass or derived class, while the other class is called a parent class, base class or super class, and the subclass will inherit some existing properties and methods in the parent class.

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

For example, in the above example, I didn't list_ Defined as a list, but it can call the append method. The reason is that the class Mylist inherits from the base class list_ It is also an instantiated object of Mylist, so list_ It will also have methods owned by the Parent class list. Of course, the inheritance relationship between the two classes can be realized in the form of user-defined classes. We define two classes, Parent and child. Child has no properties and methods, but inherits from the Parent class.

class Parent:
    def par(self):
        print('Parent method')
class Child(Parent):
    pass
child = Child()
child.par()
'''
Parent method
'''

cover

When a method or property with the same name as that in the parent class is defined in the child class, the method or property corresponding to the parent class will be automatically overwritten. Use the above example to facilitate understanding.

class Parent:
    def par(self):
        print('Parent method')
class Child(Parent):
    def par(self):
        print('Subclass method')
child = Child()
child.par()
'''
Subclass method
'''

You can see that there is more than one method in the subclass Child, which is the same name as the parent class Parent, and then instantiate the subclass and call this method, and finally call the method in the subclass. Inheritance in Python also allows multiple inheritance, that is, a subclass can inherit properties and methods from multiple parent classes, but such operations will lead to code confusion, so it is not recommended in most cases. I won't introduce it here.

polymorphic

Polymorphism is relatively simple. For example, two classes are defined. The two classes have no relationship, but there are methods with the same name in the two classes. When the instance objects of the two classes call this method respectively, the methods called by the instance objects of different classes are also different.

class XiaoMing:
    def introduce(self):
        print("I'm Xiao Ming")
class XiaoHong:
    def introduce(self):
        print("I'm Xiao Hong")

Both of the above two classes have the introduce method. We can instantiate the two classes and use the instance object to call this method to realize polymorphism.

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

In[14]:ming.introduce()
Out[14]:I'm Xiao Ming

In[15]:hong.introduce()
Out[15]:I'm Xiao Hong

Common BIF

1,isssubclass(class,classinfo)

Judge whether a class is a subclass of another class. If yes, it returns True; otherwise, it returns False.

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

There are two points to note:

  • 1. The second parameter can be passed in not only classes, but also tuples composed of classes.
  • 2. A class is determined as its own subclass, that is, when these two parameters are passed into the same class, they will also return True.

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

    2,isinstance(object,classinfo)

    Judge whether an object is an instance object of a class. If yes, 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
    

    There are two points to note:

  • 1. The second parameter can be passed in not only classes, but also tuples composed of classes.
  • 2. If the first parameter is not an object, False is always returned.

3,hasattr(object,name)

Judge whether an instance object contains a property. If yes, it returns True; otherwise, it returns False.

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

Note that the second parameter name must be passed in as a string. If not, False will be returned.

Keywords: Python

Added by simon13 on Thu, 27 Jan 2022 09:15:15 +0200