Is it possible to extend both old and new style classes?

When I expanded some of the classes generated by the tool, I did not realize that they were old-style classes until I tried to use super (). The super () function does not work with old style classes, so I got this error:

TypeError: super() argument 1 must be type, not classobj

For example, 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 curious what would happen if I continue B from the object to make it a new style class, and this seems to do the work of super ().

>>> class B(A, object):
...     def greet(self):
...         print "B says hi"
...
>>> super(B, B()).greet()
A says hi

Is this a suitable workaround or will I have some undesirable consequences later?

+5
source share
3 answers

, - , :

import re
pat = re.compile("^(.*class\s+\w+)(:.*)$")
out_file = open("edited_file.py", "w")
for line in open("generated_file.py"):
    m = pat.match(line)
    if m:
        line = m.group(1) + "(object)" + m.group(2) + "\n"
    out_file.write(line)

out_file.close()

- , , , object. , ; .

Python ( Alex Martelli, O'Reilly) , , . , . , .

+1

Python , Python 2.2. Python 3.x . .

- , - . , super(). , , , , . ( , , - .)

- Python ( "" ), - , , .

, .

+4

, , ( ).

, , class A: class A(object):.

0

All Articles