我的两个类需要具有相同的方法,但它们之间没有继承关系。
以下代码在Python 3中有效:
class A(object):
def __init__(self):
self.x = 'A'
def printmyx(self):
print(self.x)
class B(object):
def __init__(self):
self.x = 'B'
printmyx = A.printmyx
a = A()
b = B()
a.printmyx()
b.printmyx()
和打印
A
B
但是,在Python 2中,我得到了
Traceback (most recent call last):
File "py2test.py", line 18, in <module>
b.printmyx()
TypeError: unbound method printmyx() must be called with A instance as first argument (got nothing instead)
我认为问题在于,在Python 3中printmyx
只是一个常规函数,而在Python 2中则是一个未绑定的方法。
如何使代码在Python 2中工作?
edit
在我的真实代码中,A
和B
从不同的父类继承。他们需要共享一种辅助方法,但彼此之间没有其他关系。
为什么不允许继承?这是继承的完美用例。
class Common(object):
def printmyx(self):
print(self.x)
class A(Common):
def __init__(self):
self.x = 'A'
class B(Common):
def __init__(self):
self.x = 'B'
a = A()
b = B()
a.printmyx()
b.printmyx()