Understanding Python Classes and Objects
Python is fundamentally an object-oriented programming language, where virtually everything is treated as an object — each possessing properties and methods. A class in Python acts as a blueprint for constructing such objects, enabling developers to encapsulate data and functionality together in a clean, reusable format.
Creating a Class
To define a class in Python, the class
keyword is used. Below is a basic example of defining a class named MyClass with a property x
:
class MyClass:
x = 5
Instantiating an Object
After defining the class, you can create an instance (object) from it. Here’s how you instantiate the class and access its property:
p1 = MyClass()
print(p1.x)
The __init__()
Method
The __init__()
method is a special function that automatically executes when a new object is instantiated. It is commonly used to initialize object attributes:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
The __str__()
Method
The __str__()
method returns a user-friendly string representation of the object. Without it, Python returns a less readable default string:
Without __str__()
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
With __str__()
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Defining Object Methods
Methods are functions that belong to an object. They are defined within the class using the def
keyword. Here is an example of a method that prints a greeting:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
The self
Parameter
The self
parameter refers to the current instance of the class and is used to access variables that belong to the class. Although conventionally named self
, it can technically be any valid identifier:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Modifying Object Properties
Object properties can be modified directly after the object is created:
p1.age = 40
Deleting Object Properties
Properties can be removed using the del
keyword:
del p1.age
Deleting Objects
Entire objects can be deleted using the del
statement:
del p1
The pass
Statement
If a class body is intentionally left empty, use the pass
statement to avoid syntax errors:
class Person:
pass
For more Python tutorials and academic programming resources, always refer to Devyra.