Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the object declaration mean in a python class, and should I use it? [duplicate]

example #1:

class Person(object):
    pass

example #2:

class Person:
    pass

What does the object declaration do? Should you use it? I have a bunch of programs with both of them and don't know the difference it is making. If anyone can explain this concept please.

like image 562
Paxwell Avatar asked Nov 16 '12 21:11

Paxwell


People also ask

What does object in the class definition mean Python?

A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class . An object is created using the constructor of the class. This object will then be called the instance of the class.

What happens when you instantiate an object in Python?

In short, Python's instantiation process starts with a call to the class constructor, which triggers the instance creator, . __new__() , to create a new empty object. The process continues with the instance initializer, . __init__() , which takes the constructor's arguments to initialize the newly created object.

What is the use of __ str __?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.


1 Answers

In Python2, declaring object as the base class makes the class a new-style class. Otherwise, it is a "classic" class. Among the differences are that

  • Properties only work with new-style classes

  • new-style classes have the mro method

  • new-style classes have many attributes that classic classes lack

    In [288]: class Foo: pass
    In [289]: dir(Foo) 
    Out[289]: ['__doc__', '__module__']
    
    In [290]: class Bar(object): pass
    In [291]: dir(Bar) 
    Out[291]:  ['__class__',  '__delattr__',     '__dict__',  '__doc__',  '__format__',  '__getattribute__',     '__hash__',  '__init__',  '__module__',  '__new__',  '__reduce__',     '__reduce_ex__',  '__repr__',  '__setattr__',  '__sizeof__',     '__str__',  '__subclasshook__',  '__weakref__']
    

Classic classes are retained in Python2 only for backwards compatibility. All custom classes you define should be made new-style.

In Python3, all classes are new-style, so it need not be explicitly declared there.

like image 131
unutbu Avatar answered Oct 04 '22 02:10

unutbu