2
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()

BaseOneorBaseTwo中,我想使用从子类定义的变量。有没有更好的方法来完成上述操作?

4

2 回答 2

1

我看不出有任何理由不这样做。我建议first, second = None, None在基类上添加类似的东西(或创建这两个继承自的更高级别)以解决子类无法设置这些值的情况,否则应该没问题。

于 2012-07-18T15:02:55.197 回答
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!'
于 2012-07-18T15:06:29.470 回答