Grahalt
Grahalt

Reputation: 85

python initialize class and base class using class method

I am trying to initialize a derived class from text file input. A simple example of what I am trying to do:

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

Is there a good way to do this? Basically looking for something similar to what you would find in C++ with:

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

This way each class is nicely encapsulated and the base/derived classes don't need to know anything about each other (excepting __init__ which knows the number of args base takes).

Upvotes: 0

Views: 124

Answers (1)

Grahalt
Grahalt

Reputation: 85

Just realized that I was going about this the wrong way. Simple fix is to do something like:

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

Upvotes: 1

Related Questions