0

My apologies if this is a trivial question. I am trying to pass a subclass variable as an argument in the parent class __init__() but get an 'undefined name' warning.

For example: The subclass (JumpingJacks) variable PATH is considered an 'undefined name' when I try to use it in the parent class (Exercise) instantiation.

class JumpingJacks(Exercise):
    """Creates JumpingJack instance, an Exercise with default attributes
    common to the Exercise (parent) and unique to JumpingJacks:

    Exercise(name, reps, per_side=False, path=None)
    """
    PATH = "Jumping Jacks.PNG"
    def __init__(self, reps, name="Jumping Jacks"):
        Exercise.__init__(self, 
                          name, reps, 
                          per_side=False, 
                          path=PATH)

I suspect the answer relates to class inheritance, but because PATH is local during the parent class __init__(), I don't understand why PATH is undefined. I have been unable to find a succinct explanation. What part of this am I misunderstanding or doing incorrectly?

I realize I could hard-code the path into the parent class __init__() like this:

path="Jumping Jacks.PNG"

Rather than:

path=PATH

But I think its better practice to use the class variable instead if all instances share the common variable. Correct me if this way of thinking is incorrect.

How do I call the subclass variable in the parent class __init__()?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
OnStrike
  • 748
  • 1
  • 6
  • 22
  • 5
    You need to use `self.PATH`. – BrenBarn Oct 29 '14 at 18:09
  • Thanks! That answers my question completely. I am newer to SO: Should I remove the question since your comment answers it? – OnStrike Oct 29 '14 at 18:13
  • consider using `super` instead of `Exercise.__init__`, eg `super(JumpingJacks, self).__init__(name=name, reps=reps, per_side=False, path=self.PATH)` – Anentropic Oct 29 '14 at 18:14
  • @Anentropic Thanks for your input! I am newer to super() and until I understand it more fully, I am using the explicit parent class. Perhaps Ill make that my next question("When to use super()?")... – OnStrike Oct 29 '14 at 18:20
  • Yes you should make a new question and no you should not remove this one @BrenBarn should make his suggestion and answer and not a comment – ErlVolton Oct 29 '14 at 18:35

0 Answers0