classmethods Python

Содержание
Введение
Отличие метода от функции
Пример
__init__()
__init__() значения по умолчанию
self
Похожие статьи

Введение

Это продолжение статьи «Классы» из раздела «ООП в Python» .

Здесь вы можете прочитаь про classmethods

Обычные, иначе говоря, instance методы вы можете изучить здесь

Рекомендую также изучить статью «Декораторы в Python»

# Class Methods part 1. Total 8 class Employee: num_of_emps = 0 raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' Employee.num_of_emps += 1 def fullname(self): return f'{self.first} {self.last}' def apply_raise(self): self.pay = int(self.pay * self.raise_amt) # regular method automatically takes an instance as an argument # by convention it is called 'self' #class method takes class as an argument @classmethod def set_raise_amt(cls, amount): cls.raise_amt = amount emp_1 = Employee('Balda', 'Worker', 50000) emp_2 = Employee('Test', 'User', 60000) print(Employee.raise_amt) # 1.04 print(emp_1.raise_amt) # 1.04 print(emp_2.raise_amt) # 1.04 Employee.set_raise_amt(1.05) print(Employee.raise_amt) # 1.05 print(emp_1.raise_amt) # 1.05 print(emp_2.raise_amt) # 1.05 # also possible to apply to instance but # what is the point emp_1.set_raise_amt(1.06) print(Employee.raise_amt) # 1.06 print(emp_1.raise_amt) # 1.06 print(emp_2.raise_amt) # 1.06

python classmethod_example.py

1.04 1.04 1.04 1.05 1.05 1.05 1.06 1.06 1.06

Article author: Andrei Olegovich

Похожие статьи
OOP in Python
Classes
Methods
class variables
class methods
Static Methods
Inheritance
Special Methods
property decorator
Python
Functions
super()

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: