Python #inheritance (inheritance)

Python basics

Inheritance (inheritance)

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

Multiple inheritance

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

Python #inheritance (inheritance)
About python inheritance
Python
[Python] Class inheritance (super)
[Python] Class inheritance, override
[python] super (), inheritance, __init__, etc.
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
[Python of Hikari-] Chapter 09-03 Class (inheritance)
ufo-> python (3)
Python comprehension
install python
Python Singleton
python memo
Python Jinja2
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
[Python] Sort
Note: Python
Python basics ③
python log
Python basics
[Scraping] Python scraping
Python update (2.6-> 2.7)
python memo
Python # sort
ufo-> python
Python nslookup
python learning
Hannari Python 2020
[Rpmbuild] Python 3.7.3.
Class inheritance
Prorate Python (1)
python memorandum