Difference between object and instance for classes

What is the difference between this:

class ThisIsAClass(object)
    pass

print ThisIsAClass()
>> <__main__.ThisIsAClass object at 0x7f0128a8fd10>

      

and this?

class ThisIsAClass()
    pass

print ThisIsAClass()
>> <__main__.ThisIsAClass instance at 0x7f0128a8fd10>

      

+3


source to share


3 answers


The type of declaration is different. The new style classes inherit from the object or from another new style class.

class NewStyleClass(object):
    pass

class AnotherNewStyleClass(NewStyleClass):
    pass

      

There is no old style in classrooms.

class OldStyleClass():
    pass

      

Well, the new style classes inherit from object

or from other new style classes.



Prior to Python 2.1, only old style classes were used. The concept of a class (old-style) is not related to the concept of type: if x is an instance of an old-style class, then it x.__class__

denotes a class x

, but type(x)

always < type 'instance'>

, This reflects the fact that all instances of the old style, regardless of their class, are implemented with the same built-in type called an instance.

Python 2.2 introduced new style classes to unify classes and types. The new style class is nothing more than a custom type. If x

is an instance of a new style class, then type(x)

matches x.__class__

.

The main motivation for introducing new style classes is to provide a single object model with a complete metamodel.

For compatibility reasons, the classes are still the same.

Python 3 only has new style classes.

+5


source


The one that inherits from object

uses the new style class , while the other uses the old style class. Many users don't notice the difference on a daily basis, but there is a big difference in terms of multiple inheritance and what great decorators you can use. for example property

can only be used in a new style class.



New-style classes are recommended these days, so I find it a good habit to always inherit from an object unless you really have a compelling reason to avoid it. Also note that if you ever switch to python3.x, all your classes will automatically become new, so it's best to get used to them now :).

+1


source


The first is the new style class, the second is the old style class. See the documentation for differences.

+1


source







All Articles