Reputation: 21
Essentially, what is the difference in defining class using baseclass "object", vs without any baseclass. I have seen classes are defined with baseclass "object" many times.
class MyClass(object):
def __init__(self. *params):
self.params = params
Or,
class MyClass:
def __init__(self. *params):
self.params = params
Upvotes: 2
Views: 1214
Reputation: 110121
In Python 3.x, which is the de facto Python language nowadays, there are no differences at all: either have an explicit inheritance from object, or leaving the bases blank is absolutely the same thing.
For Python 2, however it is another matter -
After the language evolved Object Oriented sintaxes with what today are called "classic classes", a series of better features in the inheritance mechanisms, memory allocation, object initialization, attribute retrieval was thought of, and then object
was introduced, back in Python 2.2 as the base for what was called "new style classes" in Python 2.x life cycle.
So, if you see some code that is supposed to run in Python 2, not inheriting from object, is almost always an error - which can cause hard to find incorrect behaviors to take place at run time (for example type(instance)
will not work properly, you can't use descriptors, such as "properties" and so on).
As stated above, however, all classes in Python 3.0 and above are "new style classes". Explicitly inheriting from object is interesting when one would write code that should run correctly both in Python 2 and Python 3 - few projects today focus on keeping Python 2 compatibility, and that is why one will see less and less "object" as an explicit base in new code.
Upvotes: 2