简体   繁体   中英

python: modify array from parent method in child method

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:

  1. You are overwritting a built in function abs in your code. This should not be done.
  2. You are calling super().abilities() , which returns a value without storing and using it.
  3. When calling 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 constructor
  4. The adult abilities method is not returning anything.
  5. You are not calling the super constructor in adult, which results in adult not storing any of the values passed in the constructor.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM