Junior — Middle
Kuidas ühendada või siduda kahte klassi Pythonis, et nad töötaksid koos?
sobes.tech AI
Vastus AI-lt
In Python, there are several approaches to combine or connect two classes:
- Composition: one class contains an instance of another class as an attribute. This allows using the functionality of one class inside another.
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self):
self.engine = Engine() # Composition
def start(self):
self.engine.start()
print("Car is moving")
car = Car()
car.start()
-
Inheritance: one class inherits from another, extending or overriding its functionality.
-
Association through methods: classes can interact via methods, accepting instances of each other as parameters.
The choice of approach depends on the task and the degree of coupling between classes.