Senior
Tell me about methods in OOP (classic methods, __init__ and so on).
sobes.tech AI
Answer from AI
In object-oriented programming (OOP), methods are functions associated with classes or objects that describe the behavior of these objects.
- Class methods are regular functions within a class that can modify the object's state or perform actions.
- Constructor (
__init__in Python) is a special method called when creating an object, initializing its state. - Destructor is a method called when destroying an object, to free resources.
- Static methods are methods that do not depend on a specific object and are called through the class.
- Class methods are methods that receive the class as the first argument and can modify the class state.
Example in Python:
class Example:
def __init__(self, value):
self.value = value # object initialization
def instance_method(self):
return self.value
@classmethod
def class_method(cls):
return 'This is a class method'
@staticmethod
def static_method():
return 'This is a static method'
Methods allow encapsulating logic related to objects and provide a convenient interface for interacting with them.