Basic Python

class inheritance

Naranjito 2021. 5. 4. 19:08

1. Create parent class

class Parent:
    def can_sing(self):
        print('sing a song')

 

2. Inheritance

 

2-1. Inherit parent class with nothing

Add () after the class which I want to take the inheritance.

class LuckyChild(Parent):
    pass

pass : there is no method, variable

 

And then, create instance and call the Parent's method.

child1=LuckyChild()
child1.can_sing()
>>>
sing a song

 

2-2. Inherit parent class and embody other method to inherited class.

class Child(Parent):
    def can_dance(self):
        print('dancing')

And then, create instance and call the Parent's and its instance's method.

child=Child()
child.can_sing()
>>>
sing a song

child.can_dance()
>>>
dancing