Accessing Attributes and Methods in Python
Last Updated :
29 Mar, 2025
In Python, attributes and methods define an object's behavior and encapsulate data within a class. Attributes represent the properties or characteristics of an object, while methods define the actions or behaviors that an object can perform. Understanding how to access and manipulate both attributes and methods is important for effective object-oriented programming. Python provides built-in functions to dynamically interact with object attributes and methods. Let's explore them one by one.
Accessing Attributes
Attributes can be accessed, modified or deleted dynamically using built-in functions.
Example:
Python
class Employee:
def __init__(self, name='Harsh', salary=25000):
self.name = name
self.salary = salary
def show(self):
print(self.name)
print(self.salary)
emp1 = Employee() # Create an instance
# Access attribute
print(getattr(emp1, 'name'))
# Check attribute existence
print(hasattr(emp1, 'salary'))
# Dynamically add a new attribute
setattr(emp1, 'age', 30)
print(getattr(emp1, 'age'))
# Delete an instance attribute
delattr(emp1, 'salary')
print(hasattr(emp1, 'salary'))
OutputHarsh
True
30
False
Explanation:
- getattr() retrieves the name attribute.
- hasattr() checks if the salary attribute exists.
- setattr() dynamically adds an age attribute.
- delattr() removes the salary attribute from the class.
Accessing methods
Methods are functions defined within a class that operate on instances of that class. They can be accessed and invoked using an instance or dynamically using built-in functions.
- getattr(obj, method): Retrieves a method reference, which can then be called.
- hasattr(obj, method): Check if the method or attribute exists for a specific instance of the class.
- setattr(obj, method, function): Dynamically assigns a new method to an object.
Example:
Python
class Employee:
def __init__(self, name, salary):
self.name, self.salary = name, salary
def show(self):
return f'Name: {self.name}, Salary: {self.salary}'
emp1 = Employee("Harsh", 25000)
# Check method, invoke dynamically, and reassign
if hasattr(emp1, 'show'):
print("method exists")
print(getattr(emp1, 'show')())
#Dynamically assign a new method and invoke it
setattr(emp1, 'show', lambda: f'New method output: {emp1.name} with salary {emp1.salary}')
print(getattr(emp1, 'show')())
Outputmethod exists
Name: Harsh, Salary: 25000
New method output: Harsh with salary 25000
Explanation:
- getattr(emp1, 'show') retrieves a reference to the show method of emp1 for later invocation.
- hasattr(emp1, 'show') checks if the emp1 object has the show method, returning True if it exists, otherwise False.
- setattr(emp1, 'show', lambda: ...) dynamically assigns a new method (lambda) to the show attribute of emp1.
- getattr(emp1, 'show')() retrieves and immediately invokes the newly assigned show method.
Accessing Attributes and Methods of a Class in Another Class
Sometimes, we may need to access attributes and methods of one class inside another class. This is often achieved through inheritance or composition.
Example 1: Accessing Attributes and methods via Object Passing
Python
class ClassA:
def __init__(self):
self.var1 = 1
self.var2 = 2
def methodA(self):
self.var1 += self.var2
return self.var1
class ClassB:
def __init__(self, class_a):
self.var1 = class_a.var1
self.var2 = class_a.var2
self.methodA = class_a.methodA # Accessing method
obj1 = ClassA()
print(obj1.methodA()) # Update and print var1 (3)
obj2 = ClassB(obj1) # Copy attributes and method from ClassA
print(obj2.var1)
print(obj2.var2)
print(obj2.methodA()) # Call the method
Explanation:
- ClassA defines attributes and a method.
- ClassB copies attributes and the method reference from ClassA.
- methodA() is called on object2, demonstrating access to a method from another class.
Example 2: Accessing Attributes and methods via Inheritance
Python
class Parent:
def __init__(self):
self.parent_attr = "Parent Class"
def show(self):
print(self.parent_attr)
class Child(Parent):
def __init__(self):
super().__init__() # Inherit Parent attributes
self.child_attr = "Child Class"
def display(self):
self.show() # Access parent method
print(self.child_attr)
child = Child()
child.display()
OutputParent Class
Child Class
Explanation:
- Parent class defines an attribute and a method.
- Child class inherits from Parent, allowing access to its attributes and methods.
- super().__init__() call ensures the Parent constructor is executed.
- show() method from Parent is called, demonstrating inheritance.
Similar Reads
How to Access dict Attribute in Python In Python, A dictionary is a type of data structure that may be used to hold collections of key-value pairs. A dictionary's keys are connected with specific values, and you can access these values by using the keys. When working with dictionaries, accessing dictionary attributes is a basic function
6 min read
Accessor and Mutator methods in Python In Python, class is a prototype for objects which is a user-defined type. It specifies and defines objects of the same type, a class includes a cluster of data and method definitions. Moreover, an object is a single instance of a class but you can create many objects from a single class.Note: For mo
3 min read
Python - Access Parent Class Attribute A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
4 min read
How to Add Attributes in Python Metaclass? This article explains what a metaclass is in the Python programming language and how to add attributes to a Python metaclass. First, let's understand what a metaclass is. This is a reasonably advanced Python topic and the following prerequisites are expected You have a good grasp of Python OOP Conce
4 min read
Define and Call Methods in a Python Class In object-oriented programming, a class is a blueprint for creating objects, and methods are functions associated with those objects. Methods in a class allow you to define behavior and functionality for the objects created from that class. Python, being an object-oriented programming language, prov
3 min read
Python hasattr() method Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false. In this article, we will see how to check if an object has an attribute in Python. Syntax of hasattr() function Syntax : hasattr(obj, ke
2 min read