I've seen a few questions on this topic, but I haven't been able to find a definitive answer.
I would like to know the proper way to use old-style classes in a new Python code base. Let's say for example that I have two fixed classes, A and B. If I want to subclass A and B, and convert to new-style classes (A2 and B2), this works. However there is an issue if I want to create a new class C, from A2 and B2.
Therefore, is it possible to continue with this method, or do all classes have to conform to the old-style if any base class is defined as old-style?
See the example code for clarification:
class A:
def __init__(self):
print 'class A'
class B:
def __init__(self):
print 'class B'
class A2(A,object):
def __init__(self):
super(A2, self).__init__()
print 'class A2'
class B2(B,object):
def __init__(self):
super(B2, self).__init__()
print 'class B2'
class C(A2, B2):
def __init__(self):
super(C,self).__init__()
print 'class C'
A2()
print '---'
B2()
print '---'
C()
The output of this code:
class A
class A2
---
class B
class B2
---
class A
class A2
class C
As you can see, the problem is that in the call to C()
, class B2 was never initialized.
Update - New-Style Class Example
I guess it is not clear what the correct initialization sequence should be when using super
. Here is a working example where a call to super does initialize all base classes, not just the first one it finds.
class A(object):
def __init__(self):
super(A, self).__init__()
print 'class A'
class B(object):
def __init__(self):
super(B, self).__init__()
print 'class B'
class A2(A):
def __init__(self):
super(A2, self).__init__()
print 'class A2'
class B2(B):
def __init__(self):
super(B2, self).__init__()
print 'class B2'
class C(A2, B2):
def __init__(self):
super(C, self).__init__()
print 'class C'
C()
and produces the output:
class B
class B2
class A
class A2
class C