DEV Community

shashikantsingh
shashikantsingh

Posted on

How to display all attributes of a class in python

To display all the attributes, let's create a class name Laliga,

class Laliga:
    def __init__(self,team_name,star_palyer,coach,no_of_titles):
        self.team_name = team_name
        self.star_palyer = star_palyer
        self.coach = coach
        self.no_of_titles = no_of_titles
Enter fullscreen mode Exit fullscreen mode

The init_ method will accept the instance of that class as a self and we will have to pass the other 4 arguments.

To understand self, first, create the instance of our class, we call it "team1"

team1 = Laliga("Real madrid","Eden hazard","Zinedine zidane",34)
Enter fullscreen mode Exit fullscreen mode

so when we create method within class,it automatically receives instance of that class as the first argument which
means calling self.team_name has the same meaning as calling team1.team_name.

so now we have understood about self, go back to to printing all the attributes of team1 object to see what its attributes contain, and for that, we have to use dict method

print(team1.__dict__)
Enter fullscreen mode Exit fullscreen mode

This will print the list of all attributes and values contained in it

python class_self.py 
{'team_name': 'Real madrid', 'coach': 'Zinedine zidane', 'star_palyer': 'Eden hazard', 'no_of_titles': 34}
Enter fullscreen mode Exit fullscreen mode

now you can see the attributes of team1 object .:)

Top comments (0)