I want to change the value of attribute pen_color
in View
class permanently when I call changeColor
method and the value still permenant unless I call the method again with another color,
when I call changeColor
method the pen_color
attribute still have the same value and I don't want such thing
Is there any way to do such thing or not ?
class View:
def __init__(self):
self.pen_color = 'red'
class Button(View):
def __init__(self):
pass
def changeColor(self):
super().__init__()
self.pen_color = 'green'
CodePudding user response:
You should move the declaration of pen color into a class attribute rather than an instance attribute and reference it as View.pen_color
.
Having done that View.pen_color
will be permanent and global, but can be shadowed by self.pen_color
in either View or Button instances.
CodePudding user response:
This is not best practice, but if you really want then you can do it. To do this is to make a function to set the initial color in the superclass' __init__()
, then change that function later on. Here's an example:
class View:
def __init__(self):
self.initColor()
def initColor(self):
self.pen_color = 'red'
class Button(View):
def __init__(self):
super().__init__()
def changeColor(self, color):
def newColor(self):
self.pen_color = color
View.initColor = newColor
btn = Button()
print(btn.pen_color) # returns 'red'
btn.changeColor('green')
btn2 = Button()
print(btn2.pen_color) # returns 'green'