0

Hi all -

Working on teaching myself some python and have some code I am working on, I am at a point where I would like to update a parent class variable from within a subclass, I am wondering what is the proper method for doing this. Something similiar to below. Thank you.

Class A(object):

    def __init__(self):
        self.a = 4
        self.b = 6

class B(A):

    def __init_(self):
        #some code

    def Action(self) #some sort of parameter if real program
        #here is where i would want to update "a" from above
3
Contributors
2
Replies
47
Views
4 Years
Discussion Span
Last Post by Ene Uran
1

Well, it looks like

class A(object):  # <--- small 'c'

    def __init__(self):
        self.a = 4 # <--- a and b are instance variables (not class variables)
        self.b = 6

class B(A):

    def __init__(self): # <--- watch the number of underscores
        A.__init__(self) # <--- call parent class constructor explicitely
        #some code

    def Action(self):
        self.a = 9 # <--- update member a

Edited by Gribouillis

1

After the help Gribouillis gave you, also run a test:

class A(object):

    def __init__(self):
        self.a = 4
        self.b = 6

class B(A):

    def __init__(self):
        A.__init__(self)
        #some code

    def action(self):
        self.a = 9

# test it
aa = A()
print(aa.a)  # 4

bb = B()
print(bb.a)  # 4

bb.action()
print(bb.a)  # 9
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.