Home  >  Article  >  Backend Development  >  Classes in Python

Classes in Python

高洛峰
高洛峰Original
2016-10-19 15:19:301571browse

Although Python has advantages in Function Programming that other languages ​​cannot match, we should not forget that Python is also an OO language. Therefore, while we pay attention to Python's advantages in FP, we also need to understand Python's OO characteristics.

To discuss the OO features of Python, understanding Class in Python is naturally the first thing to do. Defining classes and creating object instances in Python is very simple. The specific code is as follows:

class GrandPa:
    def __init__(self):
        print('I\'m GrandPa')
  
  
class Father(GrandPa):
    def __init__(self):
        print('I\'m Father!')
  
class Son(Father):
    """A simple example class"""
    i = 12345
    def __init__(self):
        print('这是构造函数,son')
    def sayHello(self):
        return 'hello world'
  
if __name__ == '__main__':
    son = Son()
    # 类型帮助信息
    print('类型帮助信息: ',Son.__doc__)
    #类型名称
    print('类型名称:',Son.__name__)
    #类型所继承的基类
    print('类型所继承的基类:',Son.__bases__)
    #类型字典
    print('类型字典:',Son.__dict__)
    #类型所在模块
    print('类型所在模块:',Son.__module__)
    #实例类型
    print('实例类型:',Son().__class__)

Running status:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v. 1600 32 bit (Intel)] on win32

Type "copyright", "credits" or "license()" for more information.

>>> ================ ================ RESTART ================================

>>>>

This is the constructor, son

type help information: A simple example class

Type name: The base class inherited by the Son

type: (,)

Type dictionary: {'__module__' : '__main__', 'sayHello': , '__doc__': 'A simple example class', '__init__': , 'i': 12345}

The module where the type is located: __main__

This is the constructor, son

Instance type:

>>>>

#Python supports multiple inheritance

First of all, you will find that there is a bracket in the definition of Class, which is where inheritance is reflected. Java uses extends, C# and C++ use colons (:), and Python uses parentheses. There are two values ​​contained in the brackets. If you are smart, you will definitely find out: Python supports multiple inheritance;

#__init__ is the constructor in Class

Second point, __init__ is the constructor in Class, two different The form of constructor reflects Python's support for function overloading. In the constructor, there is a special parameter self, whose meaning is the same as this common in Java and C#. One thing needs to be emphasized here: the method defined in Class is essentially a function, but the self parameter must be included when the method is defined, and the self parameter must be placed first;

#python member variable

Three points. In Python, you do not need to explicitly declare the Data Members of the Class. Instead, when assigning a value, the assigned variable becomes the Data Members of the Class, just like x and y in the code. Not only do you not need to explicitly declare Data Members, but even more special, you can even delete the Data Members in the Class through the del method. When I first saw such a feature, I was really surprised. After all, the first point of OO is encapsulation, but does this feature destroy the characteristics of encapsulation?

#python method ambiguity problem

The fourth point is that because Python supports multiple inheritance, method ambiguity problems may occur [1]. However, because Python follows the depth-first search rule, it avoids the problem of method ambiguity. For example, in the above code, MyClass inherits from both BaseClassA and BaseClassB. Assume that MyClass calls a method called derivedMethod. DeriveMethod is defined in both BaseClassA and BaseClassB, and the Signature is exactly the same, then the method in BaseClassA will be called. If derivedMethod is not defined in BaseClassA, but the parent class of BaseClassA defines this method, derivedMethod in the parent class of BaseClassA will be called. In short, the inheritance method search path is from left to right. After selecting a BaseClass, the search will be carried out along the inheritance structure of the BaseClass until the top, and then to another BaseClass.

That’s all for now. The OO features in Python will be further described in future posts.

[1] Method ambiguity: Since a class inherits from two or more parent classes at the same time, and there are methods with exactly the same signature in these parent classes, the compiler will not be able to determine which parent the subclass will inherit. Methods in classes, leading to method ambiguity


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn