Python Classes and Objects

Python Classes and Objects – Python Ангилал ба Объектууд #

Python is an object oriented programming language.

Python бол объект хандлагат програмчлалын хэл юм.

Almost everything in Python is an object, with its properties and methods.

Python дахь бараг бүх зүйл нь шинж чанарууд, аргууд нь объект юм.

A Class is like an object constructor, or a “blueprint” for creating objects.

Ангилал нь объект үүсгэхэд ашигладаг “төлөвлөгөө” буюу объект зохион бүтээгчтэй адил зүйл юм.

Create a Class – Ангилал үүсгэх #

To create a class, use the keyword class:

Ангилал үүсгэхийн тулд class түлхүүр үгийг ашиглана:

Example – Жишээ #

Create a class named MyClass, with a property named x:

MyClass нэртэй ангилал үүсгэж, x нэртэй шинж чанартай болгоё:

class MyClass:
  x = 5

Create Object – Объект үүсгэх #

Now we can use the class named MyClass to create objects:

Одоо бид MyClass нэртэй ангилалыг ашиглан объектуудыг үүсгэж болно.

Example – Жишээ #

Create an object named p1, and print the value of x:

p1 нэртэй объект үүсгэж, x-ийн утгыг хэвлэх:

p1 = MyClass()
print(p1.x)

The __init__() Function – __init__() Функц #

The examples above are classes and objects in their simplest form, and are not really useful in real life applications.

Дээрх жишээ нь хамгийн энгийн хэлбэрийн ангиуд ба объектууд бөгөөд бодит амьдралын хэрэглээнд тийм ч хэрэгтэй биш юм.

To understand the meaning of classes we have to understand the built-in __init__() function.

Ангилалын утгыг ойлгохын тулд бид __init__() функцийн утгыг ойлгох хэрэгтэй.

All classes have a function called __init__(), which is always executed when the class is being initiated.

Бүх ангиуд __init__() гэж нэрлэгддэг функцтэй бөгөөд энэ нь ангилал эхлэх үед үргэлж ажилладаг.

Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

__init__() функцийг ашиглан объектын шинж чанаруудад утга оноох эсвэл объект үүсгэх үед хийх шаардлагатай бусад үйлдлийг хийхэд ашигладаг.

Example – Жишээ #

Create a class named Person, use the __init__() function to assign values for name and age:

Хүн нэртэй ангилал үүсгэж, __init__() функцийг ашиглан нэр болон насны утгыг оноох:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)

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

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

The __str__() Function – __str__() Функц #

The __str__() function controls what should be returned when the class object is represented as a string.

__str__() функц нь анги объект нь тэмдэгт мөр байдлаар илэрхийлэгдэх үед буцаах ёстой зүйлийг хянадаг.

If the __str__() function is not set, the string representation of the object is returned:

Хэрэв __str__() функц тогтоогдоогүй бол объектийн тэмдэгт мөр илэрхийлэл буцаагдана.

Example – Жишээ #

The string representation of an object WITHOUT the __str__() function:

__str__() функцгүй объектын тэмдэгт мөр илэрхийлэл:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
p1 = Person("John", 36)
print(p1)

Example – Жишээ #

The string representation of an object WITH the __str__() function:

__str__() функцтэй объектын тэмдэгт мөр илэрхийлэл:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def __str__(self):
    return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)

Object Methods – Объектын Аргууд #

Objects can also contain methods. Methods in objects are functions that belong to the object.

Объектууд нь аргуудыг агуулж болно. Объектын аргууд нь объектод харьяалагдах функцууд юм.

Let us create a method in the Person class:

Хүн ангид нэгэн арга оруулж үзье:

Example – Жишээ #

Insert a function that prints a greeting, and execute it on the p1 object:

Мэндчилгээ хэвлэх функц оруулж, p1 объект дээр ажиллуулах:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def myfunc(self):
    print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()

Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.

Тайлбар: self параметр нь тухайн ангилалын одоогийн жишээ рүү хандах лавлагаа бөгөөд ангид хамаарах хувьсагчдад хандахад ашиглагддаг.

The self Parameter – self параметр #

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

self параметр нь тухайн ангилалын одоогийн жишээ рүү хандах лавлагаа бөгөөд ангид хамаарах хувьсагчдад хандахад ашиглагддаг.

It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:

Энэ нь заавал self байх албагүй, та үүнийг хүссэнээрээ нэрлэж болно, гэхдээ ангиллын функцэд анхны параметр заавал байх ёстой.

Example – Жишээ #

Use the words mysillyobject and abc instead of self:

self -ийн оронд mysillyobject болон abc гэсэн үгсийг ашиглах:

class Person:
  def __init__(mysillyobject, name, age):
    mysillyobject.name = name
    mysillyobject.age = age
  def myfunc(abc):
    print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()

Modify Object Properties – Объектын Шинж чанарыг өөрчлөх #

You can modify properties on objects like this:

Объектуудын шинж чанарыг дараах байдлаар өөрчилж болно:

Example – Жишээ #

Set the age of p1 to 40:

p1-ийн насыг 40 болгох:

p1.age = 40

Delete Object Properties – Объектын Шинж чанаруудыг устгах #

You can delete properties on objects by using the del keyword:

Объектын шинж чанарыг del түлхүүр үгээр устгаж болно.

Example – Жишээ #

Delete the age property from the p1 object:

p1 объектын насны шинж чанарыг устгах:

del p1.age

Delete Objects – Объектуудыг устгах #

You can delete objects by using the del keyword:

Объектуудыг del түлхүүр үгээр устгаж болно:

Example – Жишээ #

Delete the p1 object:

p1 объектыг устгах:

del p1

The pass Statement – pass мэдэгдэл #

class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.

class-ын тодорхойлолт хоосон байж болохгүй, гэхдээ ямар нэгэн шалтгааны улмаас class-ын тодорхойлолтыг хоосон үлдээх бол pass тайлбарыг оруулж алдаа гаргахгүй байж болно.

Example – Жишээ #

The string representation of an object WITH the __str__() function:

Объектын тэмдэгт мөр илэрхийлэл __str__() функцтэй:

class Person:
  pass

Powered by BetterDocs

Leave a Reply