- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to define attributes of a class in Python?
Attributes of a class
Everything, almost everything in Python is an object. Every object has attributes and methods. Thus attributes are very fundamental in Python. A class is a construct which is a collection of similar objects. A class also has attributes. There will be a difference between the class attributes and instance attributes. The class attributes are shared by the instances of the class but it not true vice versa.
Example
We can get a list of the attributes of an object using the built-in “dir” function. For example −
>>> s = 'abc' >>> len(dir(s)) 71 >>> dir(s)[:5] ['__add__', '__class__', '__contains__', '__delattr__', '__doc__'] >>> i = 123 >>> len(dir(i)) 64 >>> dir(i)[:5] ['__abs__', '__add__', '__and__', '__class__', '__cmp__'] >>> t = (1,2,3) >>> len(dir(t)) 32 >>> dir(t)[:5] ['__add__', '__class__', '__contains__', '__delattr__', '__doc__']
As we can see, even the basic data types in Python have many attributes. We can see the first five attributes by limiting the output from “dir”;
Advertisements
To Continue Learning Please Login
Login with Google