Accessing Attributes and Methods in Python

PythonServer Side ProgrammingProgramming

As an object oriented programming language python stresses on objects. Classes are the blueprint from which the objects are created. Each class in python can have many attributes including a function as an attribute.

Accessing the attributes of a class

To check the attributes of a class and also to manipulate those attributes, we use many python in-built methods as shown below.

  • getattr() − A python method used to access the attribute of a class.

  • hasattr()  − A python method used to verify the presence of an attribute in a class.

  • setattr() − A python method used to set an additional attribute in a class.

The below program illustrates the use of the above methods to access class attributes in python.

Example

class StateInfo:
   StateName='Telangana'
   population='3.5 crore'

   def func1(self):
      print("Hello from my function")

print getattr(StateInfo,'StateName')

# returns true if object has attribute
print hasattr(StateInfo,'population')

setattr(StateInfo,'ForestCover',39)

print getattr(StateInfo,'ForestCover')

print hasattr(StateInfo,'func1')

Output

Running the above code gives us the following result −

Telangana
True
39
True

Accessing the method of a class

To access the method of a class, we need to instantiate a class into an object. Then we can access the method as an instance method of the class as shown in the program below. Here through the self parameter, instance methods can access attributes and other methods on the same object.

Example

class StateInfo:
   StateName='Telangana'
   population='3.5 crore'

   def func1(self):
      print("Hello from my function")

print getattr(StateInfo,'StateName')

# returns true if object has attribute
print hasattr(StateInfo,'population')

setattr(StateInfo,'ForestCover',39)

print getattr(StateInfo,'ForestCover')

print hasattr(StateInfo,'func1')

obj = StateInfo()
obj.func1()

Output

Running the above code gives us the following result −

Telangana
True
39
True
Hello from my function

Accessing the method of one class from another

To access the method of one class from another class, we need to pass an instance of the called class to the calling class. The below example shows how it is done.

Example

class ClassOne:
def m_class1(self):
print "Method in class 1"

# Definign the calling Class
class ClassTwo(object):
def __init__(self, c1):
self.c1 = c1

# The calling method
def m_class2(self):
Object_inst = self.c1()
Object_inst.m_class1()

# Passing classone object as an argument to classTwo
obj = ClassTwo(ClassOne)
obj.m_class2()

Output

Running the above code gives us the following result −

Method in class 1
raja
Published on 08-Jul-2019 14:42:58
Advertisements