When I extended some tool generated classes, I didn't realize that they are old style classes until I tried to use super(). The super() doesn't work with old style classes, so I got this error:
TypeError: super() argument 1 must be type, not classobj
E.g., try this snippet:
>>> class A:
... def greet(self):
... print "A says hi"
...
>>> class B(A):
... def greet(self):
... print "B says hi"
...
>>> super(B, B()).greet()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: super() argument 1 must be type, not classobj
I was just curious what would happen if I extended B from object as well to make it a new style class, and it seemed to make super() work.
>>> class B(A, object):
... def greet(self):
... print "B says hi"
...
>>> super(B, B()).greet()
A says hi
Is this an appropriate workaround or will I have some unwanted consequences later?
A new-style class is a user-defined type, and is very similar to built-in types. Old-style classes do not inherit from object . Old-style instances are always implemented with a built-in instance type. In Python 3, old-style classes were removed.
In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism.
Use the inheritance syntax class DerivedClass(BaseClass) to extend a class. Use the syntax class DerivedClass(BaseClass) to extend BaseClass as DerivedClass , so that DerivedClass inherits BaseClass .
New-style classes have been recommended practice in Python since they were introduced in Python 2.2. In Python 3.x, only new-style classes are available. Therefore, I recommend you switch your classes to new-style.
I am not aware of any real problems you might have from this. For the most part, new-style classes simply bring new features, such as super()
actually working. If you have code that relies on the semantics of old-style classes in tricky ways, that code would of course break. (The only example that comes to mind is the famous Borg pattern by the famous Alex Martelli.)
Here is a link to the Python reference manual for a discussion of new style classes vs. old-style ("classic") classes. And here is a link to the classic essay where Guido van Rossum explains why new-style classes were introduced.
I use only new-style classes in my code and I encourage you to do the same.
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