I have three classes as shown below:
class abc():
def __init__(self):
self.expiry_date = None
def some_print():
print(self.expiry_date)
class zxc(abc):
def __init__(self, expiry_date):
self.expiry_date = expiry_date
abc.__init__()
def some():
self.some_print()
class xyz(abc):
def __init__():
abc.__init__()
def cute():
self.expiry_date = date.today()
z = zxc(self.expiry_date)
z.some()
What I am trying to do is pass the variable expiry_date from class xyz to the class zxc. Class xyz creates an instance of abc so the expiry_date variable defined in the constructor of the class abc gets updated. Since, I am creating a new object of class zxc which initializes abc this variable is None again.
Is there any way I can pass expiry_date from xyz to zxc while updating the constructor variable in abc?
So, when I call z.some() I want it to print today's date.
CodePudding user response:
Your problem is captured in these lines:
class A():
def __init__(self):
self.expiry_date = None
class B(abc):
def __init__(self, expiry_date):
self.expiry_date = expiry_date
A.__init__()
First, when B gets instantiated it sets it's member field expiry_date to the value passed in. Then, it calls the super class __init__() (which, for the record, you can use super().__init__()). Then, in A, the member field for expiry_date is set to None. This is why it appears as though B is not setting that value - it is, but then it's being removed.
