Attributes Meaning in PythonIf we have been working with OOPS paradigm languages, we should've heard the word "attributes" quite often. There are two types of attributes-class attributes and instance attributes. This tutorial explains what attributes are and their types, along with examples. As Python is a huge supporter of the OOPS paradigm, everything is regarded as an object. We create classes and objects. Before understanding attributes, understanding classes and objects is the foundation. In a simple sentence, a class is like a blueprint and to use that blueprint, we create objects for that class. Example: Output: Delhi public school School: Delhi public school Place: Delhi grade: 5 Delhi public school School: Delhi public school Place: Delhi grade: 5 Understanding: In the above example, we created a class called "student" with three variables and a function that prints the values of the three variables. Every object we create for the class has access to the variables in the class. These variables are called the "Attributes", and the functions are called methods (also referred to as functions). In the above program, we created the class's two objects, s1 and s2, and accessed the attribute sch_name and the method display() printed the values of the attributes. Types of Attributes:Class Attributes:
Example: Output: Student1: Ryan Harvard Cambridge Massachusetts Boston United States Student2: Tony Harvard Cambridge Massachusetts Boston United States
Instance Attributes:
Example: Output: Student1: Ryan 18 NYU Student1: Roy 18 Duke
When we created student1: When we created student2: Both Instance attributes and Class attributes play a prominent role in creating a sound class. Here is an example using both class variables and instance variables to create a class: Output: Student1: Ryan 18 9.2 Harvard Cambridge Massachusetts Boston United States Student2: Roy 18 9.1 Harvard Cambridge Massachusetts Boston United States
Class attributes:
Instance attributes:
Function to display the attributes in a program: Python provides two built-in functions that can print the attributes of a particular object:
Example: Output: {'name': 'Ryan', 'age': 18, 'CGPA': 9.2} ['CGPA', 'Capital', 'City', 'Country', 'State', 'University', '__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__', 'age', 'name'] |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India