Reputation:
I am trying to understand python classes:
I have the following case:
class parent:
def __init__(self):
self.a = 1
self.b = 2
def printFoo(self):
print(self.a)
class child(parent):
def createC(self, val): # Create a variable inside the derived class?
self.c = val
def printFoo(self): # overloaded function
print(self.c)
a = parent()
b = child()
b.createC(3)
b.printFoo()
# Edited:
# I can even create variables as: child.d = 10
I would like to define a variable c
and store it in the child
class. Is it suitable to do this? Should I define an __init__
method to create the variable?
Best regards
Upvotes: 1
Views: 191
Reputation: 305
Do you want your variable to change ? You can simply put c
inside your new child class, such as a static class variable (have a look here maybe).
class child(parent):
c = 3
You can access it doing :
child.c
If you want to pass by the __init__()
function and define the new variable when you define the class, use the super()
method as @Ahmad Anis was suggested.
Upvotes: 0
Reputation: 2704
Yes, you can/should definitely have __init__
in the derived classes. You just need to initialize the base class via super
method. Here is the example according to your case.
class parent:
def __init__(self):
self.a = 1
self.b = 2
def printFoo(self):
print(self.a)
class child(parent):
def __init__(self):
super().__init__() # initialize base class, pass any parameters to base here if it requires any
self.c = someval
# def createC(self, val): dont need these
# self.c = val
def printFoo(self): # overloaded function
print(self.c)
If your base class requires some parameters, you can do it like this
class parent:
def __init__(self, a, b):
self.a = a
self.b = b
def printFoo(self):
print(self.a)
class child(parent):
def __init__(self, a, b, someval):
super().__init__(a, b) # initialize base class, pass any parameters to base here if it requires any
self.c = someval
#def createC(self, val): dont need these
# self.c = val
def printFoo(self): # overloaded function
print(self.c)
Upvotes: 1