What is the relationship between the type and object of Python?

Source: Internet
Author: User
Tags dashed line
It's a beginner, don't spray.
The two are mutual instances of the relationship, but not the relationship between the sub-class, only the type is a subclass of object, the other is not true. Daniel said that the two are egg-born chicken eggs, but I still do not understand, have to understand the trouble to explain, I hope not to give a link to the foreign language. Why does Python design two, remove a line?

Reply content:

explained to others many times, but writing is the first time. Try it, and I read this article (Python Types and Objects).

The relationship between object and type is much like the relationship between chicken and egg, first there is an object or first type cannot say, obejct and type are symbiotic relationship, must appear at the same time.

Before looking at it, please understand that in Python, everything is the object concept.

In object-oriented architecture, there are two kinds of relationships:
-Parent-child relationship, that is, the inheritance of the child class inherits from the parent class, such as "Snake" class inherited from the "reptile" class, we say "Snake is a kind of reptile", English said "Snake is a kind of reptile". In Python, to see the parent class of a type, use its __bases__ property to view it.
-type instance relationship, which behaves as an instantiation of a type, such as "Meng Meng is a snake", English said "Meng Meng is a instance of snake". In Python, to see the type of an instance, use its __class__ property to view it, or use the type () function to view it.

These two relationships use the following diagram to simply indicate that an inheritance relationship uses a solid line from child to parent connection, and type instance relationships use dashed lines from instance to type connections:


We will use a whiteboard to describe the relationship between objects in Python, and the whiteboard is divided into three columns:

First look at type and object:
>>> Object

>>> type

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

In the world of Python, object is the top of a parent-child relationship, and all of the data types are the parent class, and type is the top of the type instance relationship, and all objects are instances of it. Their two relationships can be described as:
-Object is a type,object is and instance of type. That is, object is an instance of type.

>>> object.__class__

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

>>> type.__bases__
( ,)
>>> type.__class__ # type is its own


At this point, the relationship of objects on the whiteboard is as follows:


Let's take a look at the built-in data types of list, dict, and tuple:
>>> list.__bases__
( ,)
>>> list.__class__

>>> dict.__bases__
( ,)
>>> dict.__class__

>>> tuple.__class__

>>> tuple.__bases__
( ,)
Both of their parent classes are object, and the types are type.

Then instantiate a list to see:
>>> mylist = [+]
>>> mylist.__class__

>>> mylist.__bases__
Traceback (most recent):
File " ", line 1, in
Attributeerror: ' List ' object has no attribute ' __bases__ '
The type of the instantiated list is , without the parent class.

Add them to the Whiteboard:
A dashed line on the whiteboard indicates that the source is an instance of the destination, and the solid lines indicate that the source is a subclass of the target. That is, the left side is the right type, and the top is the following father. A dashed line on the whiteboard indicates that the source is an instance of the destination, and the solid lines indicate that the source is a subclass of the target. That is, the left side is the right type, and the top is the following father.
Dashed lines produce relationships across columns, while solid lines can only produce relationships within one column. Except for type and object.

What does it have to do with the objects above when we set a class and instantiate it ourselves? Try it:

>>> class C (object):
... pass
...
>>> c.__class__

>>> c.__bases__
( ,)

Instantiation of
>>> C = C ()
>>> c.__class__

>>> c.__bases__
Traceback (most recent):
File " ", line 1, in
Attributeerror: ' C ' object has no attribute ' __bases__ '
This instantiated Class C object is also not a property of the parent class.
Then update the whiteboard:
The first column on the Whiteboard, currently only type, we first call this list of things type. The first column on the Whiteboard, currently only type, we first call this list of things type.
The second column on the Whiteboard, which is both the type of the third column and the instance of the first column, we call this column the object typeobject.
The third column on the Whiteboard, which is an instance of the second column type, without the parent class (__BASES__), we call them instance.

You think this is the end of the story? No.. Seeing the type alone in the first column is actually not so comfortable. Let's give it a whole couple of playmates to see. But how to complete it? To belong to the first column must be a subclass of type, then we just need to inherit the type to define the class:
>>> class M (type):
... pass
...
>>> m.__class__

>>> m.__bases__
( ,)
>>>
Well, the class m and the parent class are type. This time, we can put it in the first column. So, how do you instantiate the M type? After instantiation, should it appear in that column? Well, well, just now you accidentally created a meta class, metaclass! Class that is the class. If you are instantiating a meta-class, you have to define a class:
>>> class TM (object):
... __metaclass__ = M # To specify a meta-class.
...
...
>>> tm.__class__
# This class is no longer a type, but an M type.
>>> tm.__bases__
( ,)

Well, now the TM class is in the second column.

Let's summarize:
The first column, the Meta-class column, and the type are the fathers of all meta-classes. We can create a meta class by inheriting the type.
The second column, Typeobject column, also called Class column, object is the father of all classes, and most of the data types we use directly exist in this column.
The third column, the instance column, is the end of the object relationship chain and cannot be overridden and instantiated.

Until now, the secret of the Python type has been revealed, and the Meta class has been exposed. Hey. Slowly digest it, the amount of information is very large.

If the reporting version does not understand, then to eat a bite of the original: (Python Types and Objects)

============= Update =============
Update Update: Answer the question why do you have two, not one, behind the problem?
If type and object hold only one, then it must be an object. With only object, the first column will no longer exist, only two or three columns are left, the second column represents the type, and the third column represents the instance, which is similar to the type schema for most static languages, such as Java.
Such an architecture would leave Python with a very important dynamic feature-the dynamic creation of types. Originally, the Class (the second column of the classmate) in Python is an object (Typeobject), the object can be dynamically modified at runtime, so we can after you define a class to modify his behavior or properties! After taking out the first column, the second column becomes a pure type, written as what, and run-time behavior. At this point, there is no advantage over static language.
So, above! So I'm going to add a portal that's relevant to the idea of realization: Is there a class or an object first? -Rednaxelafx's answer
<-This portal Although the beginning of the Java situation, but also in the back of the talk of Python and Ruby, I believe that can answer the questions of the Lord some doubts. I'm going to put a picture.

The picture doesn't matter first. Let's take a look at what type and object are respectively.

The 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, object is a type (object is the kind), type is also object (type inherits from Object)
>>>isinstance(object,type)True>>>isinstance(type,object)True
In this Part I was reading about the relationship between C Sharp's object and type in MSDN. If you have a Jeffery "CLR via C #" Handy, you can read it. It may be a bit extravagant to buy one for this problem, but if you are a. NET programmer, I recommend you to receive one.

Simply put, many runtime systems (not necessarily for a particular language) provide the ability to get type information at run time, and what is obtained? Gets an object that describes the type information. Then all objects that describe the type information are instances of type type. This type is not the type itself, 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 type is also a type, it is a derivation of the common root type object, which is a reasonable design.

Turn The object type does not depend on the type, at most some of its reflection/introspection logic needs to call the type。 Object is a type that is a type that describes a type.
    1. All objects must be instances of a class
    2. The class is also an object in Python, and all classes are instances of the type meta class
    3. The type meta-class is also an object, which is its own instance, and its parent class is a
    4. Object is a class, it is an instance of type, object has no parent class

I think this is probably to complete the object-oriented, since all things are objects, then the most source of the object is whose instance? Type and object solve the problem well: grab your shoelaces and lift yourself up (bootstrap).

Novice Python, please correct me if you are wrong. All objects in Python, all objects have types.
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;
Is neither an instance of each other:
>>> object.__class__

>>> type.__class__

Nor is it an inter-subclass:
>>> object.__bases__
()
>>> type.__bases__
( ,)

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

__class__ is one of the more basic of the two relationships. All Python objects have corresponding class objects, and almost all operations on a python, even if the object property is accessed O.A so basic, is transferred to its class object execution. The exception to two is __class__ and ID, which cannot be changed by the semantics of the class object. In this respect, Python is much more customizable than most oopl.

Type is the class of all class objects, also known as Metaclass. It determines the behavior when you manipulate a class object directly, rather than through its instance. For example:
class C(object):    a = 1    def f(self):        passc = C()c.f() # 行为由C决定C.a # 行为由type决定
Before I read an article about this issue, the link has been lost ... The proposed master read "Ruby Metaprogramming", which has a clear and in-depth discussion of classes and objects, is not very demanding, the object model of Ruby and Python is very similar, and does not know how to read Ruby.

To understand this problem, first of all, the concepts of class, type, object are all out and reconstruct the world view.

first of all, Python is all objects, including type, object, all class, all objects,

What is the connection between that object? Yes, it depends on the relationship:
in Python's world, there are two relationships between objects:

1. Inheritance Relationship:
For example, there are Class A and Class B (a), and again, A and B are objects,
Object B Inherits object A, or a is a super class of B,
The inheritance relationship can be learned through the __base__ property,
Such as
>>>B.__base__<class'A'>
  • 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.