Junior — Middle
Is it possible to create an object of a class inheriting from Mixin in Python?
sobes.tech AI
Answer from AI
Yes, in Python, you can create a class object by inheriting from a Mixin. A Mixin is a class that is usually not intended for standalone use but serves to add specific functionality to other classes through multiple inheritance.
Example:
class JsonMixin:
def to_json(self):
import json
return json.dumps(self.__dict__)
class User(JsonMixin):
def __init__(self, name, age):
self.name = name
self.age = age
user = User("Alice", 30)
print(user.to_json()) # Outputs the JSON representation of the object
Thus, the User class object inherits methods from JsonMixin and can use them.