How does Python use C to realize object polymorphism?

Source: Internet
Author: User

In python, everything is an object, and all objects have the same content, which is defined in pyobject.

// XK> How to Implement inheritance

Pyobject is the base class of all (New Style) classes in Python. Its definition is very simple.

// XK> python3.2.2 _ source/include/object. h
Typedef struct _ OBJECT {
_ Pyobejct_head_extra
Py_ssize_t ob_refcnt; // XK> reference count
Struct _ typeobject * ob_type; // XK> the object type is represented by type object.
} Pyobject;

_ Pyobejct_head_extra macro, which is not compiled in Python of the release version. The pyobject struct only defines the reference count and type information. The object type is also an object (typedef _ typeobject {...} pytypeobject;). The type object is used to represent the type information.

How can we use C language to implement inheritance relationships? Subclass inherits the content of the parent class and adds and modifies it. Therefore, in the memory layout, you only need to place the content of the parent class in the header of the object, and then you can use the parent class pointer to point to the Child class object. In python, each object has the same object header-pyobejct content, which makes references to objects in Python very uniform, you only need to use a pyobject * pointer to reference any object. This is necessary to implement polymorphism.

// XK> how to represent the type

The object type defines the data members of the object and the operations that can be applied to the object. View the definition of _ typeobejct in python3.2.2 _ source/include/object. H, which contains a large number of function pointers. These function pointers indicate the operations defined by this type, that is, the behaviors of objects of this type during runtime.

In the operation information, three pointers are important: tp_as_number, tp_as_sequence, and tp_as_mapping. Taking tp_as_number as an example, it is the pynumbermethonds * pointer, And the pynumbermethonds struct defines the operations that should be supported as a numerical object. Similarly, tp_as_sequence indicates the operations supported by a sequence object, and tp_as_mapping indicates the operations supported by an associated object. Visible: in Python, an object can be a numerical object, a sequence object, or an associated object at the same time. The key is what operations it supports, that is, what non-null function pointers are defined. Therefore, the polymorphism of Python objects is behavior-based, unlike the type-based polymorphism in C ++/Java and other languages. Python objects are actually all types, and all possible function pointers are available, but many function pointers are null. As long as you implement this function, the python object can display this behavior.

>>> Class Myint (INT ):
Def _ getitem _ (self, key ):
Return key + STR (Self)

>>> A = Myint (1)
>>> B = Myint (2)
>>> Print a + B
3
>>> A ['key']
'Key1'

A subclass is defined to inherit from the built-in int class and should be a numerical object, but because the _ getitem _ method is defined, assign a new value to the null function pointer of the pytypeobejct object corresponding to Myint in Python, so that this type of object can show the characteristics of correlated objects.

// XK> Python object Polymorphism

Through pyobject and pytypeobejct, python uses C language to implement object polymorphism similar to C ++ (but different ). When you create an object in Python, such as a pyjsonbject object, python uses the pyobject * pointer instead of the pyjsonbject * pointer to save and maintain this object, in python, all functions pass a generic pointer-pyobject *. Therefore, the pointer type cannot be used to determine the object type, it can be dynamically determined only from the ob_type field of the object indicated by the pointer. As a result, Python implements the polymorphism mechanism.

// XK> chaos: Comparison between C philosophy and C ++ Philosophy

C philosophy: Keep it simple.

C ++ philosophy: use complex tools to deal with complex real-world problems, so as to obtain a simple and direct solution.

C and C ++ both realize that the essence of programming is the complexity of control, but they adopt different ideas.

The C language uses the division and control method to modularize a complex problem into many relatively simple small problems, and carefully design the communication between modules. The module can be a function, a process, or even an independent program. The UNIX tool chain philosophy is in the same line.

The C ++ meditation book states that, for traditional industries like automobile manufacturing, on the one hand, user interfaces are becoming simpler and simpler, while on the other hand, internal implementations are becoming more and more complex. We live in such a complex world, so Java and C # become increasingly complex. The complexity of C ++ comes from the complexity of the actual problems to be solved.

Theoretically, it makes no sense to argue over superiority, inferiority, and inferiority. Both of them make sense. There are some problems with C language selection. The modular design can easily lead to redundancy (each Python object must define support for all types of operations, A large number of function pointers are set to null). Using C to implement object-oriented mechanisms is obviously not as simple and straightforward as using C ++. Even so, the C language seems to be more widely supported than C ++. C ++ seems to be too complicated. It is difficult to learn, and the development efficiency is low. In the face of very complex problems, we have grasped the high requirements of the traders as a whole. Although separation and governance are inevitable, redundancy is feasible.

Finally, it is the greatest stupidity for students to choose from. Learning should be combined with projects on hand as much as possible, and the seemingly cool things on the hand should be done further than others, learn by doing it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.