我如何在不继承Python 2的情况下重用其他类的方法?

问题描述 投票:0回答:1

我的两个类需要具有相同的方法,但它们之间没有继承关系。

以下代码在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

在我的真实代码中,AB从不同的父类继承。他们需要共享一种辅助方法,但彼此之间没有其他关系。

python python-2.7
1个回答
-1
投票

为什么不允许继承?这是继承的完美用例。

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()
© www.soinside.com 2019 - 2024. All rights reserved.