Why is it better to add object when defining a class in python2, and what if it doesn't?

# -.- coding:utf-8 -.-
# __author__ = 'zhengtong'


class Person:
    """
    不带object
    """
    name = "zhengtong"


class Animal(object):
    """
    带有object
    """
    name = "chonghong"

if __name__ == "__main__":
    x = Person()
    print "Person", dir(x)

    y = Animal()
    print "Animal", dir(y)

operation result

Person ['__doc__', '__module__', 'name']
Animal ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', 
'__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']

The Person class can clearly see the difference. It does not inherit the object object, but only has doc  ,  module  and its own defined name variable, which means that only three objects in the namespace of this class can be manipulated. The 
Animal class inherits the object object and has There are a lot of operable objects, these are advanced features in the class.

For students who don't know much about python, these advanced features are basically useless, but for those who want to write frameworks or write large-scale projects, these features are more useful, such as exception capture in tornado. You can use class to locate the name of the class, and use dict to complete the highly flexible parameter transfer .

Finally, it needs to be clear. This article is based on python 2.7.10 version. In fact, in python 3, the object has been loaded for you by default (even if you did not write the object).


Source: https://blog.csdn.net/w571523631/article/details/55099385

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325815933&siteId=291194637