Classes
Classes are a fundamental concept in object-oriented programming (OOP) in Python. They allow you to create custom data types and encapsulate data and functionality together.
You can define a class using the class keyword.
class MyClass:
ㅤㅤdef __init__(self, attribute):
ㅤㅤㅤㅤself.attribute = attribute
ㅤ
ㅤㅤdef method(self):
ㅤㅤㅤㅤprint(f"This is a method. Attribute: {self.attribute}")
After defining a class, you can create objects (instances) of that class.
obj = MyClass("Hello")
obj.method()
Classes can have class variables (shared by all instances) and instance variables (unique to each instance).
class MyClass:
ㅤㅤclass_variable = "I'm a class variable"
ㅤ
ㅤㅤdef __init__(self, instance_variable):
ㅤㅤㅤㅤself.instance_variable = instance_variable
Python supports inheritance, allowing you to create a new class based on an existing class.
class ParentClass:
ㅤㅤdef parent_method(self):
ㅤㅤㅤㅤprint("This is from the parent class")
ㅤ
class ChildClass(ParentClass):
ㅤㅤdef child_method(self):
ㅤㅤㅤㅤprint("This is from the child class")
Child classes can override methods defined in their parent classes.
class ChildClass(ParentClass):
ㅤㅤdef parent_method(self):
ㅤㅤㅤㅤ# Override the parent method
ㅤㅤㅤㅤprint("This is the overridden method in ChildClass")