About Lesson
Python Classes and Objects
A class in Python is a blueprint for creating objects. An object is an instance of a class.
1. Defining a Class
To define a class in Python, you use the class
keyword followed by the class name.
Example:
class MyClass:
x = 5
2. Creating Objects
To create an object of a class, you simply call the class name followed by parentheses.
Example:
class MyClass:
x = 5
obj = MyClass()
3. Accessing Object Attributes
You can access object attributes using dot notation.
Example:
class MyClass:
x = 5
obj = MyClass()
print(obj.x) # 5
4. Modifying Object Attributes
You can modify object attributes directly.
Example:
class MyClass:
x = 5
obj = MyClass()
obj.x = 10
print(obj.x) # 10
5. Constructor Method
A constructor method (__init__()
) is a special method that is automatically called when an object is created.
Example:
class MyClass:
def __init__(self, x):
self.x = x
obj = MyClass(5)
print(obj.x) # 5
Conclusion
Classes and objects are fundamental concepts in object-oriented programming. They allow you to model real-world entities with attributes and behaviors, making your code more organized and reusable.
Join the conversation