0

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

asked Aug 13, 2016 at 20:21

1 Answer 1

1

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()
answered Aug 14, 2016 at 2:43
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.