Metody instancji i self
Proszę pisać metody operujące na danych należących do danego obiektu.
Metody instancji i self to bezpłatna lekcja Python Academy na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Python Academy, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Python Academy zawiera 4 lekcji w sumie.
Wprowadzenie
Definiowanie metod instancji
class Circle:
def __init__(self, r): self.r = r
def area(self):
import math
return math.pi * self.r**2
print(Circle(5).area())Wywoływanie metod
class Dog:
def __init__(self, name): self.name = name
def bark(self): print(f'{self.name} says Woof!')
Dog('Rex').bark()Metody zwracające self
class Builder:
def __init__(self): self.data = {}
def set(self, k, v):
self.data[k] = v
return self
def build(self): return self.data
result = Builder().set('x',1).set('y',2).build()
print(result)Metody prywatne (konwencja)
class Account:
def __init__(self, bal): self._bal = bal
def _validate(self, amount): return amount > 0
def deposit(self, amount):
if self._validate(amount):
self._bal += amount
a = Account(100)
a.deposit(50)
print(a._bal)Właściwości jako metody
class Circle:
def __init__(self, r): self.r = r
@property
def diameter(self): return self.r * 2
c = Circle(5)
print(c.diameter) # no ()Modyfikowanie stanu
class Stack:
def __init__(self): self.items = []
def push(self, x): self.items.append(x)
def pop(self): return self.items.pop()
def peek(self): return self.items[-1]
s = Stack()
s.push(1); s.push(2)
print(s.pop(), s.peek())Porównywanie obiektów
class Point:
def __init__(self, x, y): self.x,self.y=x,y
def __eq__(self, other): return self.x==other.x and self.y==other.y
print(Point(1,2)==Point(1,2))Protokół iteracji
class Countdown:
def __init__(self, n): self.n = n
def __iter__(self): return self
def __next__(self):
if self.n <= 0: raise StopIteration
self.n -= 1; return self.n + 1
print(list(Countdown(3)))Protokół menedżera kontekstu
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, *args):
import time
print(f'elapsed: {time.time()-self.start:.3f}s')
with Timer(): passMetoda a funkcja
class Dog:
def bark(self): print('woof')
print(type(Dog.bark))
print(type(Dog().bark))Szybkie sprawdzenie
Podsumowanie
Kontynuuj
Często zadawane pytania
Czy lekcja „Metody instancji i self” jest bezpłatna?
Tak — pełny tekst „Metody instancji i self” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Python Academy, przejdź na CoddyKit PRO. Kurs Python Academy zawiera 4 lekcji w sumie.
Co nauczysz się w „Metody instancji i self”?
Proszę pisać metody operujące na danych należących do danego obiektu. Ćwiczysz Python Academy z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Python Academy?
Nie wymagamy żadnego doświadczenia. Python Academy w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.
Ile czasu zajmuje lekcja „Metody instancji i self”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Python Academy?
Tak. Każda lekcja Python Academy zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Klasy i metoda __init__
- Atrybuty instancji a atrybuty klasy
- Metody instancji i self
- Metody magiczne: __str__ i __repr__