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

Recommended Answers

All 2 Replies

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

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.