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 it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.
Example:
Python3
class Student:
stream = "COE"
def __init__( self , name, roll_no):
self .name = name
self .roll_no = roll_no
a = Student( "Shivam" , 3425 )
b = Student( "Sachin" , 3624 )
print (a.stream)
print (b.stream)
print (a.name)
print (b.name)
print (Student.stream)
|
Output :
COE
COE
Shivam
Sachin
COE
Note: For more information, refer to Python Classes and Objects.
Getting a List of Class Attributes
It is important to know the attributes we are working with. For small data, it is easy to remember the names of the attributes but when working with huge data, it is difficult to memorize all the attributes. Luckily, we have some functions in Python available for this task.
Using built-in dir() Function
To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir().
Example:
Python3
class Number :
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)
n = Number( 2 )
n.show()
print ( '\nBy passing object of class' )
print ( dir (n))
print ( '\nBy passing class itself ' )
print ( dir (Number))
|
Output :
first second third 2 By passing object of class [‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘attr’, ‘one’, ‘show’, ‘three’, ‘two’] By passing class itself [‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘one’, ‘show’, ‘three’, ‘two’]
Using getmembers() Method
Another way of finding 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.
Example:
Python3
import inspect
class Number :
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)
n = Number( 2 )
n.show()
for i in inspect.getmembers(n):
if not i[ 0 ].startswith( '_' ):
if not inspect.ismethod(i[ 1 ]):
print (i)
|
Output :
first second third 2
('attr', 2)
('one', 'first')
('three', 'third')
('two', 'second')
Using __dict__() Magic Method
To find attributes we can also use magic method __dict__. This method only returns instance attributes.
Example:
Python3
class Number :
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)
n = Number( 2 )
n.show()
print (n.__dict__)
print (n.__dict__.keys())
print (n.__dict__.values())
|
Output:
first second third 2
{'attr': 2}
dict_keys(['attr'])
dict_values([2])
Using vars() function
To find attributes we can also use vars() function. This method returns the dictionary of instance attributes of the given object.
Python3
import inspect
class Number :
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)
n = Number( 2 )
n.show()
print ( vars (n))
|
Output:
first second third 2
{'attr': 2}
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Nov, 2022
Like Article
Save Article