Sobes.tech
Middle

A sinfining har bir metodini qanday chaqirish mumkin?

sobes.tech AI

AIdan javob

Faraz qilamiz, A sinfi bor va metodlari:

import time

class A:
    def what_time(self):
        return f'{time.time()}'

    @property
    def useless_getter(self):
        return self.text

    def __private_or_public(self):
        return 1

    def __str__(self):
        return self.text

    def __init__(self, text):
        self.text = text

Har bir metodni chaqirish uchun:

  • what_time — oddiy metod, obyektdan chaqiriladi:

    a = A('salom')
    print(a.what_time())
    
  • useless_getter — xususiyat, parantezsiz atribut sifatida chaqiriladi:

    print(a.useless_getter)
    
  • __private_or_public — ikki chiziqli metod, nomi o'zgaradi (name mangling), chaqirish uchun:

    print(a._A__private_or_public())
    
  • __str__ — maxsus metod, avtomatik ravishda satrga aylantirilganda chaqiriladi:

    print(str(a))
    

Shuning uchun, ikki chiziqli maxfiy metodni chaqirish uchun, sinf nomi bilan ishlatiladi: _A__private_or_public().