What is Attribute in Python
In OOP (Object-Oriented Programming) language, every object has its internal characteristics data called fields, attributes, or properties. In Python, these object-bound characteristics data are generally known as attributes.
- Class Attributes
In Python, classes are objects. It means that classes can have their own attributes.
class student: name = "Jessy" age = 15 grade = 7 print(student.name) print(student.age)
Output:
Jessy 15
Here name
, age
, grade
are the attributes of the class student
. Since these attributes are defined at the class level, they are known as class attributes. They are directly retrievable by the class.
2. Instance Attributes
In classes, we can set attributes to instance objects. These attributes are known as instance attributes. These are instance-specific data. They cannot be shared among objects.
class student: name = "Jessy" age = 15 grade = 7 def __init__(self, score, place): self.score = score self.place = place st = student(99, "Agra") print(st.place) print(st.score)
The __init__
function will serve as the construction method to create a new student
instance. The first argument self
refers to the instance that we’re creating. During the creating the new instance, we will assign the score and place information to the new instance object, and these attributes will become part of the instance’s characteristics.
Agra 99