Classes and objects are fundamental concepts in Object-Oriented Programming (OOP) and are used in many languages, including Python. In this article, we will explore how to create and work with classes and objects in Python.
Defining a Class
In Python, classes are defined using the class
keyword followed by the class name and a colon. Within the class, you can define attributes and methods.
class MyClass:
attribute = "Some value"
def my_method(self):
print("Hello from my_method")
In the example above, a class named MyClass
is created with an attribute
and a method my_method
.
Creating an Object
To create an object of a class, use the class name followed by parentheses:
my_object = MyClass()
Now we have an object named my_object
, which is an instance of the MyClass
.
Accessing Object Attributes and Methods
To access the attributes and methods of an object, use dot notation:
print(my_object.attribute) # Prints "Some value"
my_object.my_method() # Prints "Hello from my_method"
Learn Python from the Skipro online course “Python Developer”. This program is designed for beginners without any programming or technical education experience. The course is in the form of short recorded video lectures. It includes several quizzes and masterclasses. At the end of each week, there is a live meeting with development experts to answer questions and analyze homework.
Initializing an Object
The constructor of an object is defined by a special method __init__
. This method can set initial values for the object’s attributes.
class MyClass:
def __init__(self, attribute_value):
self.attribute = attribute_value
def my_method(self):
print("Hello from my_method")
Now, when creating an object of the class, you need to pass a value for the attribute:
my_object = MyClass("Custom value")
print(my_object.attribute) # Prints "Custom value"
Class Inheritance
Inheritance allows you to create a new class that inherits attributes and methods from a base class.
class ParentClass:
def method1(self):
print("Method1 of ParentClass")
def method2(self):
print("Method2 of ParentClass")
class ChildClass(ParentClass):
def method3(self):
print("Method3 of ChildClass")
Now, objects of the ChildClass
can access methods from the base class:
child_object = ChildClass()
child_object.method1() # Prints "Method1 of ParentClass"
child_object.method2() # Prints "Method2 of ParentClass"
child_object.method3() # Prints "Method3 of ChildClass"
This is how classes and objects are created in Python. These are the basics of OOP that will help you learn the language and develop programs in the future. Happy learning with Python!