1

Why does it print 0 and not 24? Also, why does it bring up an error if I dont explicitly define num in the System class even though im doing it in the constructor?

from abc import ABC, abstractmethod
class System(ABC):

    num = 0

    def __init__(self, input):
        self.num = input
        return

    @abstractmethod
    def getNum(self):
        pass

class FirstSystem(System):
    def __init__(self, input):
        super().__init__(input)
        return

    def getNum(self):
        return super().num

foo = FirstSystem(24)
print(foo.getNum())
4
  • 2
    You probably don't want both a class attribute and an instance attribute with the same name (num) in the first place. Commented Jan 27, 2022 at 16:44
  • Thanks for letting me know, I didnt even know there was a difference between the two! Commented Jan 27, 2022 at 16:47
  • Sidenote: input is a bad variable name since it shadows the builtin input function. You can see in the syntax highlighting that input is highlighted as a builtin (orange). I'd recommend using the attribute name instead, num. Commented Jan 27, 2022 at 16:52
  • On the other hand, it's only a problem if you intend to call the built-in function inside System.__init__. Commented Jan 27, 2022 at 16:57

2 Answers 2

3

Try changing

def getNum(self):
    return super().num

to

def getNum(self):
    return self.num

and see if that helps :)

Sign up to request clarification or add additional context in comments.

1 Comment

This works because super() returns a proxy for the class, not the instance, so you are explicitly asking for the value of the class attribute shadowed by the instance attribute.
1

super() explicitly calls the parent class and is used to access methods and objects that have been overwritten; ie, the exact opposite of what you want! As Capt. Trojan noted, self.num will get you the subclass version of num as you expect.

Here is the classic explaination of when and when not to use super.

1 Comment

There is no "subclass" version of num. It's an instance attribute, associated with the instance itself, without regard to which class's method might have created it (if, indeed, any method did).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.