---
title: Python Inheritance
description: "> ## Python Inheritance – Python Удамшил > > > > Inheritance allows us to define a class that inherits all the methods and properties from another class. > > > > Удамшил нь нэг ангилалын бүх аргууд болон шинж…"
url: "https://apprentice.mn/docs/python-inheritance/"
updated: "2024-07-30"
category: Python
---

# Python Inheritance

> ## Python Inheritance – Python Удамшил
>
>
>
> Inheritance allows us to define a class that inherits all the methods and properties from another class.
>
>
>
> Удамшил нь нэг ангилалын бүх аргууд болон шинж чанаруудыг өөр ангилалд өвлүүлэх боломжийг олгодог.
>
>
>
> Parent class is the class being inherited from, also called base class.
>
>
>
> Эцэг ангилал гэдэг өөр ангилалд удамшдаг ангилалыг хэлдэг ба үндсэн ангилал гэж нэрлэдэг.
>
>
>
> Child class is the class that inherits from another class, also called derived class.
>
>
>
> Хүүхэд ангилал нь өөр ангиллаас удамшдаг ангиллыг хэлдэг ба зохиомол ангилал гэж нэрлэдэг.

### Create a Parent Class – Эцэг Ангилал Үүсгэх

Any class can be a parent class, so the syntax is the same as creating any other class:

Аливаа ангилал нь эцэг ангилал байж болох тул синтакс нь бусад ангилал үүсгэхтэй адил байдаг:

#### Example – Жишээ

Create a class named `Person`, with `firstname` and `lastname` properties, and a `printname` method:

`Person` нэртэй ангилалыг `firstname` болон `lastname` шинж чанаруудтай, `printname` аргыг агуулан үүсгэе:

`class Person:  def __init__(self, fname, lname):    self.firstname = fname    self.lastname = lname  def printname(self):    print(self.firstname, self.lastname)#Use the Person class to create an object, and then execute the printname method:x = Person("John", "Doe")x.printname()`

### Create a Child Class – Хүүхэд Ангилал Үүсгэх

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:

Өөр ангиллаас удамших боломжтой ангилал үүсгэхдээ эцэг ангиллыг параметр болгон өгнө:

#### Example – Жишээ

Create a class named `Student`, which will inherit the properties and methods from the `Person` class:

`Person` ангиллаас шинж чанар, аргуудыг өвлөх `Student` нэртэй ангиллыг үүсгэх:

`class Student(Person):  pass`

**Note:** Use the `pass` keyword when you do not want to add any other properties or methods to the class.

**Тайлбар:** Ангилалд ямар нэгэн шинж чанар эсвэл арга нэмэхгүй бол `pass` түлхүүр үгийг ашиглана.

Now the Student class has the same properties and methods as the Person class.

Одоо `Student` ангилал нь `Person` ангилалын бүх шинж чанар, аргуудыг өвлөнө.

#### Example – Жишээ

Use the `Student` class to create an object, and then execute the `printname` method:

`Student` ангиллыг ашиглан объект үүсгэж, `printname` аргыг гүйцэтгэх:

`x = Student("Mike", "Olsen")x.printname()`

### Add the __init__() Function – __init__() Функцийг Нэмэх

So far we have created a child class that inherits the properties and methods from its parent.

Одоогоор бид эцэг эхээсээ шинж чанар, аргуудыг өвлөн авсан хүүхэд анги үүсгэсэн.

We want to add the `__init__()` function to the child class (instead of the `pass` keyword).

Бид `__init__()` функцийг хүүхэд ангилалд нэмэхдээ `pass` түлхүүр үгийг орлуулна.

**Note:** The `__init__()` function is called automatically every time the class is being used to create a new object.

**Тэмдэглэл:** `__init__()` функц нь шинэ объект үүсгэх бүрт автоматаар дуудагддаг.

#### Example – Жишээ

Add the `__init__()` function to the `Student` class:

`Student` ангилалд `__init__()` функцийг нэмэх:

`class Student(Person):  def __init__(self, fname, lname):    #add properties etc.`

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

`__init__()` функцийг нэмэхэд хүүхэд ангилал нь эцгийн `__init__()` функцийг цаашид өвлөхгүй.

**Note:** The child’s `__init__()` function **overrides** the inheritance of the parent’s `__init__()` function.

**Тэмдэглэл:** Хүүхдийн `__init__()` функц нь эцгийн `__init __()` функцийг хэрэглэх боломжгүй болгоно.

To keep the inheritance of the parent’s `__init__()` function, add a call to the parent’s `__init__()` function:

Эцэг ангиллаас удамшсан`__init__()` функцыг үлдээхын тулд, эцэг ангиллын `__init__()` функцийг дуудаж нэмэх хэрэгтэй.

#### Example – Жишээ

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

Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the `__init__()` function.

Одоо бид `__init__()` функцийг амжилттай нэмж, эцэг ангийн удамшлыг хадгалсан ба `__init__()` функцэд функц нэмэхэд бэлэн боллоо.

### Use the super() Function – `super()` Функцийг Ашиглах

Python also has a `super()` function that will make the child class inherit all the methods and properties from its parent:

`super()` функц нь хүүхэд ангилал эцэг ангиллын бүх арга, шинж чанарыг өвлөх боломжийг олгодог:

##### Example – Жишээ

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

By using the `super()` function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.

`super()` функцийг ашигласнаар эцэг элементийн нэрийг ашиглах шаардлагагүй бөгөөд энэ нь автоматаар эцгийн  арга, шинж чанарыг өвлөн авах болно.

   

### Add Properties – Шинж чанарууд Нэмэх

##### Example – Жишээ

Add a property called `graduationyear` to the `Student` class:

`Student` ангилалд `graduationyear` нэртэй шинж чанар нэмэх:

`class Student(Person):  def __init__(self, fname, lname):    super().__init__(fname, lname)    self.graduationyear = 2019`

In the example below, the year `2019` should be a variable, and passed into the `Student` class when creating student objects. To do so, add another parameter in the __init__() function:

Жишээн дээр `2019` он нь хувьсагч байх ёстой бөгөөд оюутан объектуудыг үүсгэх үед `Student` ангилалд оруулна. Үүний тулд `__init__()` функцэд өөр параметр нэмээрэй:

   

#### Example – Жишээ

Add a `year` parameter, and pass the correct year when creating objects:

Хувьсагч `year` нэмээд, объектыг үүсгэх үед жилээ оруулж өгнө:

`class Student(Person):  def __init__(self, fname, lname, year):    super().__init__(fname, lname)    self.graduationyear = yearx = Student("Mike", "Olsen", 2019)`

### Add Methods – Аргууд Нэмэх

##### Example – Жишээ

Add a method called `welcome` to the `Student` class:

`Student` ангилалд `welcome` нэртэй арга нэмэх:

`class Student(Person):  def __init__(self, fname, lname, year):    super().__init__(fname, lname)    self.graduationyear = year  def welcome(self):    print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)`

If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.

Хэрэв та эцэг классын функцтэй ижил нэртэй функц эсвэл аргыг хүүхдийн класст нэмж оруулбал, эцэг классын функцийн удамшлыг дардаг. Энэ нь хүүхдийн класс дахь функц нь эцэг классын функцийн оронд ашиглагдах бөгөөд хүүхэд класс функцэд давуу эрх олгоно.

            [https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-inheritance%2F&linkname=Python%C2%A0Inheritance](https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-inheritance%2F&linkname=Python%C2%A0Inheritance)[https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-inheritance%2F&linkname=Python%C2%A0Inheritance](https://www.addtoany.com/add_to/mastodon?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-inheritance%2F&linkname=Python%C2%A0Inheritance)[https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-inheritance%2F&linkname=Python%C2%A0Inheritance](https://www.addtoany.com/add_to/email?linkurl=https%3A%2F%2Fapprentice.mn%2Fdocs%2Fpython-inheritance%2F&linkname=Python%C2%A0Inheritance)[https://www.addtoany.com/share](https://www.addtoany.com/share)
