class Person(object):
pass
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With