0

可以说我有,

class A(object):
    def __init__(self, var):
        print("The parent class is A")
    def methodA(self):
        print("This method should only be accessed by a child of class A")

class B(object):
    def __init__(self, var):
        print("The parent class is B")
    def methodB(self):
        print("This method should only be accessed by a child of class B")

class C(A, B):
    def __init__(self, var):
        # if var=='a':
        #     make this class the child of only class A
        #     i.e. it should only access methods of class A
        #     and forget methods of class B.
        # if var=='b':
        #     make this class the child class B
        #     i.e. it should only access methods of class B
        #     and forget methods of class A.
        pass 

我怎样才能做到这一点?准确地说,我想创建一个派生自两个类的类,但根据输入参数,我想禁用其中一个类并仅使用另一个类的属性。所以我得到这个,

>>> c = C('a')
>>> c.methodA()
This method should only be accessed by a child of class A
>>> c.methodB()
# A not implemented error or a maybe a custom error message.
4

1 回答 1

0

如果你想这样做,我会推荐 user2357112 在评论中建议的工厂方法:

def C(parameter):
    if parameter == "a":
        return(A())
    else:
        return(B())

当然这些不是子类,所以如果你想给它添加方法/属性,你需要更多的魔法。您可能可以通过元类来实现它。

于 2016-06-07T18:20:49.910 回答