开发者

Why is it that you don't have to declare (object) for a class that only has __init__ in python? [duplicate]

This question alr开发者_StackOverflow中文版eady has answers here: Is it necessary or useful to inherit from Python's object in Python 3.x? (2 answers) Closed 2 years ago.

Thanks for helping a n00b

Example of what I am talking about:

class Complex:
    def __init__(self,x,y):
        self.x = x
        self.y = y

Why is it that when you declare the class, you don't have to add (object) to it,

class Complex(object):


class Complex1:
    def __init__(self,x,y):
        self.x = x
        self.y = y

>>> dir(Complex1)
['__doc__', '__init__', '__module__']    

class Complex2(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

>>> dir(Complex2)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__']


In Python 2.x, this makes your class old-style, with a different inheritance semantics. Since you don't use inheritance (and the method resolution order is the same in simple cases), it makes no difference in practice. If you're programming in Python 2.x, you should add (object) to profit from the advantages of new-style classes.

In Python 3.2, object is simply the default class you inherit from, and can be left out.


When you define the class simply like this class Complex you don't inherit the class from any other class and hence it only has those attributes which you define like __init__ (and __doc__ and __module__.) This is a an old-style class.

When you define a class like this - class Complex(object), it means you inherit the class from the class object. As a result, many of its attributes are inherited automatically without the need to yourself define them again like __str__, __class__ , etc. This is new style class.

In python 2.x, new style classes are usually preferred as using old style classes may lead to some problems. For example, __slots__, super, descriptors don't work in old style classes.

Old style classes have been kept in python 2.x just to maintain a backward compatibility. In python 3, this is cleaned up and any class you define is a new style class.

(Also, from what you say, inheriting from object has nothing to do with only defining __init__.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜