Python OOP
__ - private @property - getter annotation @nameOfProperty.setter - setter annotation
class Human:
def __init__(self, name, age):
self.__name = name
self.__age = age
def __del__(self):
print('Destructor called, Human deleted.')
def get_name(self):
return self.__name
@property
def age(self):
return self.__age
def set_name(self, name):
self.__name = name
@age.setter
def age(self, age):
if 0 < age < 100:
self.__age = age
else:
raise ValueError('Age must be between 0 and 100')
def say_hello(self):
print('Hello ' + self.__name)
print('Age ' + str(self.__age))
from mypackage.Human import Human
def main():
person = Human("Sam", 29)
# person.set_age(-12)
person.say_hello()
print(person.age)
person.age = -12
print(person.age)
main()
Атрибути класу та атрибути екземпляру:
class Student:
academy = "Mate academy" # class attribute
def __init__(self, name: str, course: str):
self.name = name # instance attribute
self.course = course # instance attribute
fe_student = Student("Joseph", "Frontend")
py_student = Student("John", "Python")
print(fe_student.name) # Joseph
print(py_student.name) # John
print(fe_student.__dict__) # {'name': 'Joseph', 'course': 'Frontend', 'academy': 'MATE ACADEMY'}
print(py_student.__dict__) # {'name': 'John', 'course': 'Python'}
print(Student.academy) # Mate academy
Class Method
A class method is a method that is bound to a class rather than its object. It doesn't require the creation of a class instance.
The class method can be called both by the class and its object:
class Student:
course = "python"
@classmethod
def change_student_course(cls, new_course: str):
cls.course = new_course
Student.change_student_course("frontend")
print(Student.course) # frontend
Static Method
A static method does not receive an implicit first argument. A static method is also a method that is bound to the class and not the object of the class. This method can’t access or modify the class state. It is present in a class because it makes sense for the method to be present in class.
The static method can be called both by the class and its object as well:
class Car:
@staticmethod
def miles_to_km(miles: int):
print(round(miles * 1.61, 2))
Car.miles_to_km(25) # 40.25
car = Car()
car.miles_to_km(25) # 40.25
Class Methods - when you need to work with class attributes Static Methods - when you don't need neither self(object) nor cls(class) attributes
Magic Methods
There are a lot of other magic methods, for example: __del__, __repr__, __str__, __add__, __eq__, __lt__, etc.
class User:
def __init__(self, name: str, surname: str):
self.name = name
self.surname = surname
def __str__(self):
return f"{self.name} {self.surname}"
user = User("Joseph", "Farrell")
print(user) # Joseph Farrell
__str__ - for user-friendly interpretation like "Joseph Farrell" __repr__ - for programmer unambiguous output like "User(name=Joseph, surname=Farrell)"
Якщо в методі класу потрібно повертати цей клас, то треба імпортувати або:
або (для версії python 3.11 +)from __future__ import annotations
class RockBand:
def __init__(self, name: str, members: list[str]) -> None:
self.name = name
self.members = members
def add_new_member(self, new_member: str) -> None:
if new_member in self.members:
print(f"{new_member} is already in the band!")
else:
self.members.append(new_member)
def __add__(self, other: RockBand) -> RockBand:
return RockBand(f"{self.name} {other.name} United", list(set(self.members + other.members)))