Python, as an object-oriented programming language, is renowned for its simplicity and readability. One of the core concepts in Python is the class object. This guide will delve into what class objects are, and how they function, and provide examples to help you understand.
What is a Class Object in Python?
In Python, everything is an object, and a class is no exception. A class is a code template for creating objects. Objects have member variables and behavior associated with them. In Python, a class is created by the keyword class
.
class MyClass:
x = 5
In the above example, MyClass
is an object (an instance of a class) with a property x
.
Creating Class Objects
To create a class object, you simply call the class using the class name followed by parentheses.
p1 = MyClass()
print(p1.x)
In this case, p1
is now an object of the MyClass
class.
The __init__() Function
The __init__()
function is a built-in function that gets called when a class is instantiated. It’s used to assign values to object properties or other operations that are necessary when the object is being created.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
In this example, Person
is a class with __init__()
function that takes two parameters name
and age
. When we create a new Person
object, we need to provide these parameters.
Class Methods
Classes in Python can also contain methods. Methods in objects are functions that belong to the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greeting(self):
print("Hello, my name is " + self.name)
p1 = Person("John", 36)
p1.greeting()
In this example, greeting
is a method in the Person
class. We can call this method using the object p1
.