Python

[Basic Grammar] Python Inheritance

grace21110 2023. 11. 21. 21:24
반응형
  • Python Inheritance 

Inheritance allows us to define a class that inherits all the methods and properties from another class. 

 

Parent class (base class) is the class being inherited.

Child class(derived class) is the class that inherits from another class.

 

Example 

Create a class named Christmas with month, date properties. 

class Christmas: 
 def__init__(self, month, date)"
    self.month = month 
    self.date = date
    
    def printname (self)" 
    print (self.month, self.date)
   
  X = Christmas("December", "25")
  X.printname()

 

  • Add the __init__ Function 

It is called automatically every time the class is being used to create a new object. 

 

Example 

Add the __init__ () function to the Parent class; 

class Parent(Person):
 def __init__ (self, fname, lname):

** When you add the __init__() function, the child class will no longer inherit the parent's __init__() function. **

 

  • super() function 

It makes the child class inherit all the methods and properties from its parents.

Example 

class Student(Person):
  def __init__(self, fname, lname):
    super().__init__(fname, lname)

 

  • Add properties 
class Parents(Person):
  def __init__(self, fname, age):
    super().__init__(fname, age)
    self.job = engineer

In this code, you just added the property below the super statement. Engineer is a variable and passed into the Parents class when creating parents objects.