Skip to content

8-dars: OOP — Class va Object

Dars

Davomiyligi: 90 daqiqa Maqsad: Object-Oriented Programming asoslari — class, object, method, inheritance.

1. OOP nima?

OOP (Object-Oriented Programming) — dasturlash paradigmasi. Ob'ektlarga asoslangan.

Tushunchalar:

  • Class — tur belgilash (oddiy: chizma)
  • Object — class'ning instansiyasi (chizma asosida yaratilgan)
  • Attribute — ob'ektning xususiyati (struct field)
  • Method — ob'ektga tegishli funksiya

2. Birinchi class

python
class Talaba:
    def __init__(self, ism, yosh):
        self.ism = ism
        self.yosh = yosh

# Object yaratish
t1 = Talaba("Akmal", 22)
t2 = Talaba("Aziza", 19)

print(t1.ism)   # Akmal
print(t2.yosh)  # 19

3. __init__ — konstruktor

python
def __init__(self, ism, yosh):
    self.ism = ism
    self.yosh = yosh
  • __init__ — object yaratilganda avtomatik chaqiriladi
  • self — bu object'ning o'zi (C'dagi this)
  • self.ism = ism — attribute belgilash

4. Method

python
class Talaba:
    def __init__(self, ism, yosh):
        self.ism = ism
        self.yosh = yosh
    
    def salomlash(self):
        print(f"Salom, men {self.ism}man")
    
    def yoshi_oshirish(self):
        self.yosh += 1

t = Talaba("Akmal", 22)
t.salomlash()        # Salom, men Akmalman
t.yoshi_oshirish()
print(t.yosh)        # 23

Methodlar — funksiyalar, lekin birinchi parameter self.

Chaqirilganda — self avtomatik uzatiladi.

5. C'dagi struct vs Python class

C:

c
typedef struct {
    char ism[50];
    int yosh;
} Talaba;

Talaba t;
strcpy(t.ism, "Akmal");
t.yosh = 22;

Python:

python
class Talaba:
    def __init__(self, ism, yosh):
        self.ism = ism
        self.yosh = yosh

t = Talaba("Akmal", 22)

Asosiy farq: Python class'da methods ham bor. C struct'da yo'q.

6. To'liq misol

python
class Talaba:
    def __init__(self, ism, yosh, ball):
        self.ism = ism
        self.yosh = yosh
        self.ball = ball
    
    def info(self):
        print(f"{self.ism}, {self.yosh} yosh, ball: {self.ball}")
    
    def baho(self):
        if self.ball >= 90:
            return "A"
        elif self.ball >= 80:
            return "B"
        elif self.ball >= 70:
            return "C"
        elif self.ball >= 60:
            return "D"
        else:
            return "F"
    
    def otdimi(self):
        return self.ball >= 60

# Ishlatish
t1 = Talaba("Akmal", 22, 85)
t2 = Talaba("Aziza", 19, 92)
t3 = Talaba("Botir", 25, 55)

t1.info()
print(t1.baho())       # B
print(t1.otdimi())     # True

t3.info()
print(t3.otdimi())     # False

7. __str__ — string representation

python
class Talaba:
    def __init__(self, ism, yosh):
        self.ism = ism
        self.yosh = yosh
    
    def __str__(self):
        return f"Talaba({self.ism}, {self.yosh})"

t = Talaba("Akmal", 22)
print(t)   # Talaba(Akmal, 22)

print(obj) avtomatik __str__ chaqiradi.

8. Class variable vs Instance variable

python
class Talaba:
    # Class variable — hammaga bir xil
    universitet = "TATU"
    
    def __init__(self, ism):
        # Instance variable — har object'da boshqa
        self.ism = ism

t1 = Talaba("Akmal")
t2 = Talaba("Aziza")

print(t1.universitet)   # TATU
print(t2.universitet)   # TATU

Talaba.universitet = "TIIAME"
print(t1.universitet)   # TIIAME (hammasiga ta'sir)

9. Methods turlari

python
class Talaba:
    universitet = "TATU"
    
    def __init__(self, ism):
        self.ism = ism
    
    # Instance method (eng keng tarqalgan)
    def info(self):
        print(self.ism)
    
    # Class method
    @classmethod
    def yangi_universitet(cls, name):
        cls.universitet = name
    
    # Static method
    @staticmethod
    def yordam():
        print("Yordam matni")

Talaba.yangi_universitet("TIIAME")
Talaba.yordam()

10. Inheritance — meros

python
class Odam:
    def __init__(self, ism, yosh):
        self.ism = ism
        self.yosh = yosh
    
    def salomlash(self):
        print(f"Salom, men {self.ism}")

class Talaba(Odam):     # Odam'dan meros oladi
    def __init__(self, ism, yosh, ball):
        super().__init__(ism, yosh)  # ota class konstruktor
        self.ball = ball
    
    def baho(self):
        return "A" if self.ball >= 90 else "B"

class Oqituvchi(Odam):
    def __init__(self, ism, yosh, fan):
        super().__init__(ism, yosh)
        self.fan = fan
    
    def dars_berish(self):
        print(f"{self.ism} {self.fan} darsini bermoqda")

t = Talaba("Akmal", 22, 95)
o = Oqituvchi("Botir", 45, "Matematika")

t.salomlash()         # ota class method
print(t.baho())       # o'z method
o.dars_berish()

11. Method overriding

python
class Hayvon:
    def ovoz(self):
        print("Hayvon ovozi")

class It(Hayvon):
    def ovoz(self):    # override
        print("Vov vov!")

class Mushuk(Hayvon):
    def ovoz(self):
        print("Miyov!")

h = Hayvon()
i = It()
m = Mushuk()

h.ovoz()    # Hayvon ovozi
i.ovoz()    # Vov vov!
m.ovoz()    # Miyov!

Polymorphism — bir xil method nomi, har class'da boshqa ishlash.

12. Encapsulation — yashirish

python
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self._balance = balance       # _ — "private" konventsiya
        self.__pin = "1234"           # __ — qattiqroq private
    
    def deposit(self, amount):
        if amount > 0:
            self._balance += amount
    
    def withdraw(self, amount, pin):
        if pin != self.__pin:
            print("Xato PIN")
            return False
        if amount > self._balance:
            print("Yetarli pul yo'q")
            return False
        self._balance -= amount
        return True
    
    def get_balance(self):
        return self._balance

acc = BankAccount("Akmal", 1000)
acc.deposit(500)
acc.withdraw(200, "1234")
print(acc.get_balance())  # 1300

Python "private"

Python'da haqiqiy private yo'q. Konventsiya:

  • _name — "private" (foydalanmang)
  • __name — name mangling (_ClassName__name bo'lib o'zgartiriladi)

13. Property

python
class Kvadrat:
    def __init__(self, tomon):
        self._tomon = tomon
    
    @property
    def yuza(self):
        return self._tomon ** 2
    
    @property
    def perimetr(self):
        return self._tomon * 4

k = Kvadrat(5)
print(k.yuza)        # 25 (method emas, attribute kabi)
print(k.perimetr)    # 20

@property — method'ni attribute kabi ishlatish.

14. Misol: Geometry

python
class Shape:
    def yuza(self):
        pass  # subclass'da override
    
    def perimetr(self):
        pass

class Doira(Shape):
    PI = 3.14159
    
    def __init__(self, r):
        self.r = r
    
    def yuza(self):
        return self.PI * self.r ** 2
    
    def perimetr(self):
        return 2 * self.PI * self.r
    
    def __str__(self):
        return f"Doira(r={self.r})"

class Tortburchak(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = h
    
    def yuza(self):
        return self.w * self.h
    
    def perimetr(self):
        return 2 * (self.w + self.h)

class Uchburchak(Shape):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
    
    def yuza(self):
        # Heron formula
        s = self.perimetr() / 2
        return (s * (s - self.a) * (s - self.b) * (s - self.c)) ** 0.5
    
    def perimetr(self):
        return self.a + self.b + self.c

# Ishlatish
shakllar = [
    Doira(5),
    Tortburchak(4, 6),
    Uchburchak(3, 4, 5)
]

for sh in shakllar:
    print(f"Yuza: {sh.yuza():.2f}, Perimetr: {sh.perimetr():.2f}")

15. Real misol: Library

python
class Book:
    def __init__(self, title, author, year):
        self.title = title
        self.author = author
        self.year = year
        self.is_borrowed = False
    
    def __str__(self):
        status = "Olingan" if self.is_borrowed else "Mavjud"
        return f"{self.title} ({self.author}, {self.year}) - {status}"

class Library:
    def __init__(self, name):
        self.name = name
        self.books = []
    
    def add_book(self, book):
        self.books.append(book)
    
    def show_books(self):
        for book in self.books:
            print(book)
    
    def borrow(self, title):
        for book in self.books:
            if book.title == title:
                if book.is_borrowed:
                    print(f"{title} allaqachon olingan")
                    return False
                book.is_borrowed = True
                print(f"{title} olindi")
                return True
        print(f"{title} topilmadi")
        return False
    
    def return_book(self, title):
        for book in self.books:
            if book.title == title:
                book.is_borrowed = False
                print(f"{title} qaytarildi")
                return

# Foydalanish
lib = Library("Toshkent")
lib.add_book(Book("Python", "Author 1", 2024))
lib.add_book(Book("C Programming", "K&R", 1988))
lib.add_book(Book("Algorithms", "CLRS", 2009))

lib.show_books()
lib.borrow("Python")
lib.show_books()
lib.return_book("Python")

Topshiriqlar

1 — Birinchi class

first.py:

python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        print(f"Salom, men {self.name}, {self.age} yoshda")

p = Person("Akmal", 22)
p.greet()

2 — Talaba class

student.py — Dars matnidagi to'liq class.

Bonus: update_score, compare_with methodlar.

3 — Geometry

geometry.py — Doira, Tortburchak, Uchburchak.

4 — Bank account

bank.py:

python
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
    
    def deposit(self, amount):
        ...
    
    def withdraw(self, amount):
        ...
    
    def __str__(self):
        ...

Funksionallik to'liq qiling.

5 — Inheritance

animals.py:

python
class Animal:
    def __init__(self, name):
        self.name = name
    
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        print("Vov!")

class Cat(Animal):
    def sound(self):
        print("Miyov!")

class Cow(Animal):
    def sound(self):
        print("Moo!")

6 — Library

library.py — Dars matnidagi to'liq dastur.

7 — Property

temperature.py:

python
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    
    @property
    def celsius(self):
        return self._celsius
    
    @property
    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32
    
    @property
    def kelvin(self):
        return self._celsius + 273.15

t = Temperature(25)
print(t.celsius)
print(t.fahrenheit)
print(t.kelvin)

8 — __str__

vector.py:

python
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return f"({self.x}, {self.y})"
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2     # operator overloading
print(v3)         # (4, 6)

9 — Mini To-do (OOP)

todo_oop.py:

python
class Task:
    def __init__(self, title):
        self.title = title
        self.done = False
    
    def mark_done(self):
        self.done = True

class TodoList:
    def __init__(self):
        self.tasks = []
    
    def add(self, title):
        self.tasks.append(Task(title))
    
    def show(self):
        for i, t in enumerate(self.tasks, 1):
            mark = "✓" if t.done else " "
            print(f"{i}. [{mark}] {t.title}")
    
    def mark_done(self, idx):
        if 0 < idx <= len(self.tasks):
            self.tasks[idx - 1].mark_done()

10 — GitHub

bash
$ mkdir 6-oy-dars-8
$ git add . && git commit -m "feat: dars 8 - OOP" && git push

Lug'at

TerminIzoh
ClassChizma
Object / InstanceClass'dan yaratilgan
AttributeOb'ekt xususiyati
MethodOb'ektga tegishli funksiya
selfthis — ob'ektning o'zi
__init__Konstruktor
__str__String representatsiya
InheritanceMeros
PolymorphismBir method, har class'da boshqa
EncapsulationYashirish (_ , __)
Property@property decorator
super()Ota class chaqirish

Keyingi dars

9-dars: Modullar va pip →

Master IT o'quv markazi — o'qitish rejasi