What Are Properties in a Class?
A property is a variable that belongs to:
-
an object (instance property), or
-
a class (class property)
Properties hold the state/data of objects.
Instance Properties :
Instance properties are variables unique to each object.
They are usually defined using self inside the __init__( ) method.
Accessing Instance Properties :
Python
class Student: def __init__(self, name, age): self.name = name # instance property self.age = age # instance property s1 = Student("Rahul", 22) s2 = Student("Anita", 21) print(s1.name, s1.age) print(s2.name, s2.age)Class Properties :
Class properties are variables shared by all objects of the class.
They are defined inside the class but outside methods.
Accessing Class Properties :
Python
class Student: school = "ABC School" # class property def __init__(self, name): self.name = name s1 = Student("Rahul") s2 = Student("Anita") print(s1.school) print(s2.school) Modifying Class Properties :
Python
Student.school = "XYZ School" Delete Properties :
Python
class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("Linus", 30) del p1.age print(p1.name) # This works # print(p1.age) # This would cause an error