Reputation: 509
I want to subclass by extending a method that always has the same first stage, say:
class Data:
def show(self):
# this part is common for all subclasses
total=10
class PrintA(Data):
def show(self):
Data.show(self)
print(total)
class PrintAPlus(Data):
def show(self):
Data.show(self)
print(total+10)
However, I get NameError: name a is not defined
.
How to reuse total
variable from the superclass's method?
(The obvious one is to save it as instance's attribute, but I don't need there, actually.)
Upvotes: 1
Views: 490
Reputation: 8510
the problem here is that total
is only assigned inside the superclass method show
, there is just a local variable. its value can't be see outside it.
to fix it you need to make it a instance attribute or return that value from there
option 1
class Data:
def show(self):
# this part is common for all subclasses
self.total = 10
class PrintA(Data):
def show(self):
Data.show(self)
print(self.total)
class PrintAPlus(Data):
def show(self):
Data.show(self)
print(self.total+10)
option 2
class Data:
def show(self):
# this part is common for all subclasses
return 10
class PrintA(Data):
def show(self):
total = Data.show(self)
print(total)
class PrintAPlus(Data):
def show(self):
total = Data.show(self)
print(total+10)
Upvotes: 2