all Python 3OOPterm
Instance methods
methods
The ordinary methods of a class. Their first parameter is self (a reference to the instance). They can read and change its state.
Syntax
def method(self, ...): ...
self isn't a keyword — it's just the conventional name of the first parameter, and Python passes the instance into it automatically, so obj.method(x) is sugar for Class.method(obj, x). That's why you must spell out self in the definition even though you never pass it at the call site.
Examples
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def perimeter(self):
return 2 * (self.w + self.h)
r = Rectangle(3, 4)
print(r.area()) # → 12
print(r.perimeter()) # → 14
class Stack:
def __init__(self):
self._data = []
def push(self, item):
self._data.append(item)
return self # цепочка
def pop(self):
return self._data.pop()
def peek(self):
return self._data[-1]
s = Stack()
s.push(1).push(2).push(3)
print(s.pop()) # → 3
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def to_fahrenheit(self):
return self.celsius * 9/5 + 32
def to_kelvin(self):
return self.celsius + 273.15
t = Temperature(100)
print(t.to_fahrenheit()) # → 212.0
print(t.to_kelvin()) # → 373.15
# Метод вызывает другой метод
class Circle:
def __init__(self, r):
self.r = r
def area(self):
import math
return math.pi * self.r ** 2
def scale(self, factor):
self.r *= factor
return self.area()
c = Circle(5)
print(c.scale(2)) # → 314.159...
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError('Insufficient funds')
self.balance -= amount
acc = BankAccount(100)
acc.deposit(50)
acc.withdraw(30)
print(acc.balance) # → 120
class WordCounter:
def __init__(self):
self._words = []
def add(self, text):
self._words.extend(text.split())
def count(self):
return len(self._words)
def most_common(self):
from collections import Counter
return Counter(self._words).most_common(3)
wc = WordCounter()
wc.add('the cat sat on the mat')
print(wc.count()) # → 6
See also
Open in the full glossarydocs.python.orgReport an inaccuracy