Specify the name of the base class to inherit from with ()
.
__init__
is a reserved word for Python
.
Variables are defined in self
in __ init __
.
class Say:
def printHello(self, msg):
print(msg)
class SayHello (Parent):
def __init__(self):
super(SayHello, self).__init__()
self.say = 'Hello'
self.target = 'World'
h = SayHello()
print(h.say)
print(h.target)
h.printHello(h.say + ',' + h.target)
Execution result
Hello World Hello,World
You can create a new class with multiple classes as base classes. The order you specify is important because it means the priority that is called when you call a method that is common between base classes.
class Howareyou:
def printmsg(self):
print('How are you')
class Nicetometyou:
def printmsg(self, target):
print('Nice to meet you, ' + self.target)
class Say(Howareyou, Nicetomeetyou):
pass
a = Howareyou()
a.printmsg()
b = Nicetomeetyou()
b.printmsg('Python')
c = Say()
c.printmsg()
# c.printmsg ('Python') This will result in an error.
Execution result
How are you Nice to meet you, Python How are you
Recommended Posts