I have a parent class as follows:
class student:
def __init__(self, name, age, field):
self.name = name
self.age = age
self.field = field
def abilities(self):
abs = ["study", "drink", "party"]
action = np.random.choice(abs, replace = True)
return(action)
Now upon graduation this student becomes a grown-up and his abilities change:
class adult(student):
def abilities(self):
super().abilities()
abs.append("work")
abs.remove("party")
if action == work:
print("paying off that student loan")
This does not work. The error I get is: name 'abs' is not defined
.
Now I tried to access the abilities
method in the parent class by using super().abilities.abs
but then I am referring to the object the function returns and with self.abilities.abs
, but then I refer to the class.
Any suggestions as to how to access the array within the parent method from the child are much appreciated.
There are a few flaws in the code you wrote:
abs
in your code. This should not be done.super().abilities()
, which returns a value without storing and using it.abs.append("work")
you are trying to assign a value to a build in function and not the local variable abs
from the parent. Extracting this to a object variable solves the issue. See, self.abs
in the constructorabilities
method is not returning anything.A fixed version could look as follows:
import numpy as np
class student:
def __init__(self, name, age, field):
self.name = name
self.age = age
self.field = field
self.abs = ["study", "drink", "party"]
def abilities(self):
action = np.random.choice(self.abs, replace = True)
return action
class adult(student):
def __init__(self, name, age, field):
super(adult, self).__init__(name, age, field)
self.abs.append("work")
self.abs.remove("party")
def abilities(self):
action = super().abilities()
if action == "work":
print("paying off that student loan")
return action
In addition to solving this issue, you should review the object inheritance structure as mentioned in the comment by @chepner.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.