Python Documentation

Classes

Classes in Python

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.

Defining a Class

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}")

Creating Objects

After defining a class, you can create objects (instances) of that class.

obj = MyClass("Hello")
obj.method()

Class and Instance Variables

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

Inheritance

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")

Method Overriding

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")