all Python 3OOPterm
class
classes
A class declaration. A class is the template objects (instances) are created from.
Syntax
class ИмяКласса:
тело
The class body runs once when the class is defined, not each time you create an object. Names bound directly in the body (not via self) become class attributes shared by every instance, so a mutable list or dict placed there easily turns into accidentally shared state.
Examples
class Dog:
pass # пустой класс
d = Dog()
print(type(d)) # → <class '__main__.Dog'>
class Cat:
"""Класс кошки."""
species = 'Felis catus' # атрибут класса
print(Cat.species) # → Felis catus
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'Point({self.x}, {self.y})'
p = Point(3, 4)
print(p) # → Point(3, 4)
class Circle:
pi = 3.14159
def __init__(self, r):
self.r = r
def area(self):
return self.pi * self.r ** 2
c = Circle(5)
print(c.area()) # → 78.53975
class Empty:
"""Docstring."""
pass
print(Empty.__doc__) # → Docstring.
class Counter:
count = 0
def __init__(self):
Counter.count += 1
Counter(); Counter()
print(Counter.count) # → 2
class Vehicle:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
def describe(self):
return f'{self.brand} @ {self.speed}km/h'
v = Vehicle('BMW', 200)
print(v.describe()) # → BMW @ 200km/h
See also
Open in the full glossarydocs.python.orgReport an inaccuracy