What is the relationship between python type and object?

Source: Internet
Author: User
For beginners, Do not spray. The two are examples of each other, but not subclass of each other. Only type is the subclass of object, and vice versa. Daniel said that they are the relationship between eggs, chickens, and eggs, but I still don't understand it. If you have any understanding, I 'd like to explain it. Why is it impossible to remove one line when designing two python statements? Not for beginners.
The two are instances of each other, but not subclass of each other. Only type is the subclass of the object, and vice versa. Daniel said that they are the relationship between eggs, chickens, and eggs, but I still don't understand it. If you have any understanding, I 'd like to explain it. Why is it impossible to remove one line when designing two python statements? Reply content: I have explained it to others many times, but it is the first time I write it as a text. Try it. I have read this article (Python Types and Objects.

The relationship between object and type is similar to that between chicken and eggs. There is an object first or a type first. obejct and type are symbiotic and must appear at the same time.

Before reading this article, you must first understand that everything in Python is an object concept.

There are two relationships in the object-oriented system:
-Parent-child relationship, that is, the inheritance relationship, represents that the Child class inherits from the parent class. For example, the "snake" class inherits from the "crawler" class. We say "snake is a crawler 』, in English, "snake is a kind of reptile 』. You can view a type parent class in python using its _ bases _ attribute.
-The relationship between instance types is represented by the instantiation of a certain type. For example, "Meng is a snake". In English, "Meng is an instance of snake 』. To view the type of an instance in python, use its _ class _ attribute to view it, or use the type () function to view it.

The two relationships are illustrated in the following figure. The inheritance relationship uses a solid line from the child to the parent connection, and the type instance relationship uses a dotted line from the instance to the type connection:


We will use a whiteboard to describe the relationship between objects in Python. The Whiteboard is divided into three columns:

Let's take a look at type and object:
>>> Object

>>> Type

They are all type instances, indicating that they are all type objects.

In the Python world, an object is at the top of the parent-child relationship, and all data types are parent classes; type is at the top of the type instance relationship, and all objects are its instances. The relationship between them can be described as follows:
-Object is a type, object is and instance of type. That is, an Object is an instance of type.

>>> Object. _ class __

>>> Object. _ bases _ # The object has no parent class because it is the top of the chain.
()
-Type is an object, type is kind of object. That is, Type is a subclass of the object.

>>> Type. _ bases __
( ,)
>>> Type. _ class _ # The type of type is your own


In this case, the relationship between objects on the whiteboard is as follows:


Let's look at the built-in data types such as list, dict, and tuple:
>>> List. _ bases __
( ,)
>>> List. _ class __

>>> Dict. _ bases __
( ,)
>>> Dict. _ class __

>>> Tuple. _ class __

>>> Tuple. _ bases __
( ,)
Their parent classes are all objects and all types are type.

Instantiate a list to see:
>>> Mylist = [1, 2, 3]
>>> Mylist. _ class __

>>> Mylist. _ bases __
Traceback (most recent call last ):
File" ", Line 1, in
AttributeError: 'LIST' object has no attribute '_ bases __'
The instantiated list type is Without the parent class.

Add them to the whiteboard:
The dotted line on the whiteboard indicates that the source is the target instance, and the solid line indicates that the source is a subclass of the target. That is to say, the type on the left is the type on the right, and the above is the father below. The dotted line on the whiteboard indicates that the source is the target instance, and the solid line indicates that the source is a subclass of the target. That is to say, the type on the left is the type on the right, and the above is the father below.
The dotted line is used to generate relationships across columns, while the solid line can only generate relationships within one column. Except for type and object.

When we decide a class and instantiate it, what is the relationship with the above objects? Try:

>>> Class C (object ):
... Pass
...
>>> C. _ class __

>>> C. _ bases __
( ,)

Instantiation
>>> C = C ()
>>> C. _ class __

>>> C. _ bases __
Traceback (most recent call last ):
File" ", Line 1, in
AttributeError: 'C' object has no attribute '_ bases __'
The instantiated Class C object also has no attributes of the parent class.
Update the whiteboard:
The first column on the whiteboard. Currently, only type is available. Let's name this column "Type" first. The first column on the whiteboard. Currently, only type is available. Let's name this column "Type" first.
The second column on the whiteboard is both the type of the third column and the instance of the first column. We call the object in this column TypeObject.
In the third column on the whiteboard, they are instances of the second column type without the parent class (_ bases _). We call them instances.

What do you think is the end? No .. It is not so comfortable to see that type is unique in the first column .. Let's show it a few playmates. But how can this problem be solved? To belong to the first column, it must be a subclass of type, so we only need to inherit type to define the class:
>>> Class M (type ):
... Pass
...
>>> M. _ class __

>>> M. _ bases __
( ,)
>>>
Well, both the M class type and the parent class are type. At this time, we can put it into the first column. So how can we instantiate M type? Which column should it appear in after instantiation? Well, well, you just accidentally created a MetaClass! Class. If you want to instantiate a metaclass, you still need to define a class:
>>> Class TM (object ):
... _ Metaclass _ = M.
...
...
>>> TM. _ class __
# This class is not of the type, but of the M type.
>>> TM. _ bases __
( ,)

Now, the TM class appears in the second column.

Summary:
The first column is the metadata column. type is the father of all metadata classes. We can create a metadata class by inheriting the type.
The second column is the TypeObject column, also known as the class column. The object is the father of all classes, and most of the data types we use directly exist in this column.
The third column is the instance column. The instance is the end of the object relationship chain and cannot be subclass or instantiated.

So far, the secrets of the Python type have been mentioned, and even the metaclasses are exposed accidentally. Ah. Take it easy, with a large amount of information.

If you cannot understand the record version, read the original article: (Python Types and Objects)

================ Update ====================
Update .. To answer the question, the subject explains why there are two, not one.
If only one type and object are retained, it must be an object. When only objects exist, the first column will no longer exist, with only two or three columns left. The second column indicates the type and the third column indicates the instance. This is similar to the type Architecture of most static languages, such as java.
This architecture will make python lose a very important dynamic feature-the dynamic creation type. Originally, the class (the second column of students) is an object (typeobject) in Python, which can be dynamically modified at runtime, so we can modify the behavior or attribute of a class after you define it! After the first column is removed, the second column is of the pure type, and the runtime behavior is as follows. At this point, it is not more advantageous than static languages.
So, the above! Let me add a portal related to the implementation idea: First Class or first Object? -Redna xelafx
<-Although this portal starts with Java, it will be followed by Python and Ruby, and I believe it can solve some of the doubts of the Q & A owner. I want to show a picture first

If the image is correct, ignore it first. Let's take a look at what type and object are.

Type is actually:

#define PyVarObject_HEAD_INIT(type, size)       \    1, type, size,PyTypeObject PyType_Type = {    PyVarObject_HEAD_INIT(&PyType_Type, 0)    "type",                                     /* tp_name */    sizeof(PyHeapTypeObject),                   /* tp_basicsize */    sizeof(PyMemberDef),                        /* tp_itemsize */    0,                                          /* tp_base */    ...}
Thank you! The object is type (the object type is type), and the type is also object (the type is inherited from the object)

>>> isinstance(object, type)True>>> isinstance(type, object)True
I read the relationship between objects and types in C Sharp in MSDN ...... If you have Jeffery's CLR via C #, read it. It may be a luxury to buy one for this purpose, but if you are a. net programmer, I recommend you collect one.

To put it simply, many runtime systems (not necessarily for a certain language) provide the function of retrieving type information during runtime. So what is obtained? The obtained object is a description type information object. All the objects describing the type information are "type" instances. This type is not a type, but an object instance that describes the type, The type itself is an abstract information, and the Instance Object of the type class is its specific information carrier.. Since the type is also a type, it is a derivation of the common root type object, that is, a reasonable design.

Conversely, The object type does not depend on the type. At most of its reflection/introspection logic needs to call the type. Object is a type, and type is a description type.
  1. All objects must be instances of a certain class.
  2. In python, classes are also objects, and all classes are type meta-class instances.
  3. The type meta-class is also an object, and it is its own instance. Its parent class is an object.
  4. Object is a class, it is an instance of type, and the object has no parent class

I think this is probably to complete the object orientation. since everything is an object, who is the most source object? Type and object solve this problem well: Grab your own shoelaces and lift yourself (bootstrap ).

New to python, please correct me. Everything in Python is an object, and everything has a type.
From cpython/object. h at 2.7 · python/cpython · GitHub

/* PyObject_HEAD defines the initial segment of every PyObject. */#define PyObject_HEAD                   \    _PyObject_HEAD_EXTRA                \    Py_ssize_t ob_refcnt;               \    struct _typeobject *ob_type;
Neither instance nor instance:
>>> Object. _ class __

>>> Type. _ class __

It is not a subclass of each other:
>>> Object. _ bases __
()
>>> Type. _ bases __
( ,)

Both type and object are type instances, and type is a subclass of object.

_ Class _ is a more basic of the two relationships. All Python objects have corresponding class objects, and almost all operations on a Python object are transferred to the class Object for execution even when the object attribute o. a is accessed. The only exception is _ class _ and id. the semantics of these two operations cannot be changed by the class object. In this regard, Python is more customizable than most OOPL.

Type is the class of all class objects, also known as metaclass. It determines the behavior when you directly operate the class Object (rather than through its instance. For example:

Class C (object): a = 1 def f (self): passc = C () c. f () # The behavior is determined by C. a # The behavior is determined by type.
I have read an article about this issue, and the link has been lost... It is recommended that the subject read "Ruby metaprogramming". This book has a clear and in-depth discussion of classes and objects, with low requirements. The object models of Ruby and Python are very similar, ruby is easy to understand.

To understand this problem, First, we need to remove all the concepts of classes, types, and objects and reconstruct the world view.

First, everything in python is an object, including type, object, and all classes. All objects are objects,

What are the links between objects? Yes, it depends on the relationship:
In the world of Python, there are two relationships between objects:

1. inheritance relationship:
For example, class A and class B (A) are both objects,
Then object B inherits the superclass of object A, or A is B,
The inheritance relationship can be learned through the _ base _ attribute,
For example

>>> B.__base__
                             
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.