A class is a user defined prototype from which objects are created. Classes provide a means of building of data and functionality together. Creating a new class creates a new type of object, allowing a new instances of that type to be made. Class instances an also have methods for modifing its states.
Getting a list of class attributes
It is important to know the attributes we are working with. For small data we can remember the names of attributes but when working with huge data, it is difficult to memorise all the attributes.
we have some functions in python available for this task.
Using getmembers() method
To get a list of attributes is by using the module inspect.This module provides a method called getmembers()that returns a list of class attributes and methods.
import inspect
class number :
#class Attributes
one = 'first'
two = 'second'
three = 'third'
def __init__(self, attr):
self.attr = attr
def show(self):
print(self.one, self.two, self.three, self.attr)
#Drivers code
n = Numbers(2)
n.show()
for i in inspect.getmembers(n):
#to remove private and protected function
if not i[0].startswith('_'):
#to remove other methods that doesnot start with underscore
if not inspect.ismethod(i[1]):
print(i)
Output:
first second third 2
('attr', 2)
('one', 'first')
('three', third')
'two', 'second')