python使用类方法初始化类和基类

时间:2016-08-13 20:21:22

标签: class python-3.x inheritance initialization

我正在尝试从文本文件输入初始化派生类。我想要做的一个简单例子:

file.txt的:

1
2

main.py:

class Base:
    def __init__(self, val1):
        self.val1 = val1
    def input_from_text(cls, init_deque):
        #return cls(init_deque.popleft())

class Derived(Base):
    def __init__(self, val1, val2):
        Base.__init__(self, val1)
        self.val2 = val2
    def input_from_text(cls, init_deque):
        #initialize base and derived here and return derived

def main(argv=None):
    initialized_derived = Derived.input_from_text(deque(open("file.txt")))
    assert initialized_derived.val1 is 1
    assert initialized_derived.val2 is 2

这样做有好办法吗?基本上寻找类似于C ++中的内容:

//calls operator>>(Base) then operator>>(Derived)
cin >> initialized_derived;

这样每个类都被很好地封装,基类/派生类不需要知道彼此的任何事情(除了__init__,它知道args基数的数量)。

1 个答案:

答案 0 :(得分:1)

刚才意识到我正在以错误的方式解决这个问题。简单的解决方法是执行以下操作:

class Base:
    def __init__(self):
        pass
    def input_from_text(self, init_deque):
        self.val1 = init_deque.popleft()

class Derived(Base):
    def __init__(self):
        Base.__init__(self)
    def input_from_text(self, init_deque):
        Base.input_from_text(self, init_deque)
        self.val2 = init_deque.popleft()