在Python多重继承中,父类使用子定义变量有多糟糕?

时间:2012-07-18 14:57:45

标签: python multiple-inheritance

class BaseOne(object):

    def base_one(self):
        print self.first
        print self.second
        # Do stuffs with self.first and self.second defined from sub class


class BaseTwo(object):

    def base_two(self):
        print self.first
        print self.second
        # Do stuffs with self.first and self.second defined from sub class


class Stackoverflow(BaseOne, BaseTwo):

    def __init__(self):
        super(Stackoverflow, self).__init__()
        self.first = 'Stack'
        self.second = 'Overflow'


class Serverfault(BaseOne, BaseTwo):

    def __init__(self):
        super(Serverfault, self).__init__()
        self.first = 'Server'
        self.second = 'Fault'

Stackoverflow().base_one()
Serverfault().base_one()

BaseOneBaseTwo中,我想使用从子类定义的变量。有没有更好的方法来做到这一点?

2 个答案:

答案 0 :(得分:1)

我认为没有理由不这样做。我建议在基类上添加类似first, second = None, None的东西(或者创建一个更高级别,这两个继承),以解释子类未能设置这些值的情况,但否则这应该没问题。< / p>

答案 1 :(得分:1)

这与其他语言的抽象类基本相同。没有理由不这样做。除了你可能在这里弄脏了水 - 确保你的代码可以理解。

我可能会:

class BaseOne(object):
    def base_one(self):
        print self.first()
        print self.second()

    def first(self):
        return "bad boy, don't call this on abstract instance"

    def second(self):
        return 'really, son, you have a problem here. Go create some instances of subclasses!'