Python is a widely-used programming language known for its simplicity and readability. In this section, we will explore the basics of Python classes and how they are used to create objects.
What is a Class?
A class in Python is a blueprint for creating objects. It defines the properties and behaviors that the objects of the class will have.
Class Structure
A class is defined using the class
keyword, followed by the class name and a colon. Inside the class, we define methods and attributes that define the behavior and properties of the class.
class MyClass:
def __init__(self, value):
self.value = value
def display(self):
print(self.value)
In the above example, MyClass
is a class with an attribute value
and a method display
.
Creating Objects
To create an object from a class, we use the ()
operator.
my_object = MyClass(10)
In the above example, my_object
is an instance of MyClass
with the value 10
.
Accessing Attributes and Methods
Once an object is created, we can access its attributes and methods using the .
operator.
print(my_object.value) # Output: 10
my_object.display() # Output: 10
Inheritance
Python supports inheritance, which allows us to create a new class based on an existing class. The new class is called a subclass, and the existing class is called a superclass.
class SubClass(MyClass):
def __init__(self, value, extra_value):
super().__init__(value)
self.extra_value = extra_value
def display_extra(self):
print(self.extra_value)
In the above example, SubClass
is a subclass of MyClass
. It inherits the value
attribute and display
method from MyClass
and adds an additional attribute extra_value
and a method display_extra
.
Further Reading
For more information on Python classes, you can visit the Python documentation on classes.