Introduction
In Python, attributes and methods are important concepts in Object-Oriented Programming (OOP).
Attributes represent the data or properties of an object, while methods represent the actions or behaviors that an object can perform.
For example, consider a Car object:
- Color → Attribute
- Brand → Attribute
- Start Engine → Method
- Stop Engine → Method
What are Attributes in Python?
Attributes are variables that belong to a class or an object.
They store data related to an object.
Example:
class Student:
def __init__(self):
self.name = "John"
self.age = 20
In this example:
self.name
self.age
are attributes that store information about a student.
Why Use Attributes?
Attributes help:
- Store object data
- Represent object properties
- Keep related information together
- Make code more organized
- Improve readability
For example:
A student may have:
- Name
- Age
- Roll Number
- Marks
All of these can be stored as attributes.
What are Methods in Python?
Methods are functions defined inside a class. They represent the actions that an object can perform.
Example:
class Student:
def greet(self):
print("Hello Student")
Here:
greet() is a method. It performs an action when called.
Why Use Methods?
Methods help:
- Perform operations on object data
- Encapsulate functionality
- Improve code reusability
- Organize business logic
Examples:
- Calculate salary
- Display student details
- Deposit money
- Withdraw money
- Send email
Syntax of Attributes and Methods
class ClassName:
def __init__(self):
self.attribute = value
def method_name(self):
# method code
Example:
class Student:
def __init__(self):
self.name = "John"
def display(self):
print(self.name)
Accessing Attributes
Attributes are accessed using the dot (.) operator.
Example:
class Student:
def __init__(self):
self.name = "John"
student = Student()
print(student.name)
Output:
Explanation:
The object’s name attribute is accessed using:
student.name
Calling Methods
Methods are also accessed using the dot operator.
Example:
class Student:
def greet(self):
print("Hello Student")
student = Student()
student.greet()
Output:
Explanation:
The method is called using:
student.greet()
Attributes and Methods Together
Example:
class Student:
def __init__(self, name):
self.name = name
def display(self):
print("Student Name:", self.name)
student = Student("Emma")
student.display()
Output:
Explanation:
- name is an attribute.
- display() is a method.
- The method uses the attribute.
Types of Attributes in Python
Python mainly provides two types of attributes:
1. Instance Attributes
Instance attributes belong to individual objects.
Example:
class Student:
def __init__(self, name):
self.name = name
student1 = Student("John")
student2 = Student("Emma")
print(student1.name)
print(student2.name)
Output:
Emma
Each object stores its own value.
2. Class Attributes
Class attributes are shared by all objects.
Example:
class Student:
school = "ABC School"
Accessing class attributes:
class Student:
school = "ABC School"
student1 = Student()
student2 = Student()
print(student1.school)
print(student2.school)
Output:
ABC School
Both objects share the same attribute.
Types of Methods in Python
Python supports three main types of methods.
1. Instance Methods
Most commonly used methods.
Example:
class Student:
def greet(self):
print("Hello")
student = Student()
student.greet()
Output:
Instance methods work with object data.
2. Class Methods
Class methods operate on class-level data.
Example:
class Student:
school = "ABC School"
@classmethod
def show_school(cls):
print(cls.school)
Student.show_school()
Output:
3. Static Methods
Static methods do not access instance or class data.
Example:
class Math:
@staticmethod
def add(a, b):
return a + b
print(Math.add(5, 3))
Output:
Static methods behave like regular functions inside a class.
Real-Life Examples:
1. Student Management System
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display(self):
print("Name:", self.name)
print("Marks:", self.marks)
student = Student("John", 85)
student.display()
Output:
Marks: 85
Explanation:
Attributes:
name
marks
Method:
display()
2. Bank Account
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def show_balance(self):
print("Balance:", self.balance)
account = BankAccount(
"John",
5000
)
account.deposit(2000)
account.show_balance()
Output:
Attributes:
- owner
- balance
Methods:
- deposit()
- show_balance()
Modifying Attributes
Attributes can be updated after object creation.
Example:
class Student:
def __init__(self, name):
self.name = name
student = Student("John")
student.name = "Michael"
print(student.name)
Output:
Deleting Attributes
Use the del keyword.
class Student:
def __init__(self):
self.name = "John"
student = Student()
del student.name
The attribute is removed from the object.
Attributes vs Methods
| Feature | Attributes | Methods |
|---|---|---|
| Purpose | Store Data | Perform Actions |
| Type | Variables | Functions |
| Called Using | obj.attribute | obj.method() |
| Stores Values | Yes | No |
| Executes Code | No | Yes |
Example:
class Student:
def __init__(self):
self.name = "John"
def greet(self):
print("Hello")
Attribute:
student.name
Method:
student.greet()
Advantages of Attributes and Methods
| Advantage | Description |
|---|---|
| Better Organization | Keeps data and behavior together |
| Reusability | Objects can be reused |
| Encapsulation | Protects and manages data |
| Readability | Easier to understand |
| Scalability | Suitable for large projects |
Common Mistakes
1. Forgetting self
Incorrect:
class Student:
def greet():
print("Hello")
Correct:
class Student:
def greet(self):
print("Hello")
2. Accessing Undefined Attributes
Incorrect:
student.age
Correct:
when age doesn’t exist.
Always define attributes before using them.
3. Calling Methods Without Parentheses
Incorrect:
student.greet
Correct:
student.greet()
4. Using Class Attributes as Instance Attributes
Incorrect:
class Student:
name = ""
Better:
class Student:
def __init__(self, name):
self.name = name
5. Modifying Shared Class Attributes Accidentally
Be careful when changing class-level data because it affects all objects.
Best Practices
1. Use Meaningful Attribute Names
Good:
self.student_name
Bad:
self.x
2. Keep Methods Focused
Each method should perform one task.
Use Instance Attributes for Object-Specific Data
self.name
self.age
3. Use Class Attributes for Shared Data
school = "ABC School"
4. Follow Naming Conventions
Methods:
calculate_salary()
display_info()
Use snake_case naming.
Conclusion
Attributes and methods are the core building blocks of Object-Oriented Programming in Python. Attributes store the data associated with an object, while methods define the actions that the object can perform.
Together, they allow developers to create organized, reusable, and maintainable code that closely models real-world entities.
Python Attributes and Methods – Interview Questions
Q 1: What is an attribute in Python?
Q 2: What is a method in Python?
Q 3: How do you access an object’s attribute?
Q 4: Can a method modify object attributes?
Q 5: What is the difference between class and instance attributes?
Python Attributes and Methods – Objective Questions (MCQs)
Q1. Which of the following is used to access an attribute of an object in Python?
Q2. What will be the output of the following code?
class Test:
x = 10
obj = Test()
print(hasattr(obj, 'x'))
Q3. Which built-in function is used to get all attributes and methods of an object?
Q4. What does the setattr() function do in Python?
Q5. Given the code below, what will obj.method() print?
class Demo:
def method(self):
print("Hello from method")
obj = Demo()
obj.method()