Python Classes and Objects
Classes and objects are fundamental concepts in object-oriented programming (OOP). A class is a blueprint for creating objects, and an object is an instance of a class.
Defining a Class
You can define a class in Python using the class
keyword, followed by the class name and a colon. For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Creating Objects
To create an object of a class, you use the class name followed by parentheses. You can also pass arguments to the class's constructor (the __init__
method) to initialize the object. For example:
person1 = Person('Alice', 30)
person2 = Person('Bob', 25)
Accessing Object Attributes
You can access an object's attributes using dot notation. For example, to access the name
attribute of person1
:
print(person1.name) # Output: 'Alice'
Methods
Classes can also have methods, which are functions that belong to the class. For example, adding a method to Person
to print the person's information:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f'{self.name} is {self.age} years old')
You can then call this method on a Person
object:
person1.info() # Output: 'Alice is 30 years old'
Conclusion
Classes and objects are essential concepts in OOP, allowing you to create reusable and organized code. By understanding how to define classes, create objects, and work with attributes and methods, you can leverage the power of OOP in your Python programs.