- Attributes are variables that belong to an object or class.
- There are two important types:
Instance Attribute
- Different objects can have different values.
student1 = Student("Punitha", 22)
student2 = Student("Anu", 21)
print(student1.name)
print(student2.name)
Output:
Vijay
Anu
Class Attribute
- A class attribute is shared by objects.
class Student:
college = "ABC College"
student1 = Student()
student2 = Student()
print(student1.college)
print(student2.college)
Output:
ABC College
ABC College
Methods
- A method is a function defined inside a class.
class Student:
def study(self):
print("Student is studying")
student1 = Student()
student1.study()
Output:
Student is studying
There are three commonly discussed method types:
- Instance Method
- Class Method
- Static Method
Instance Method
- An instance method works with an object.
class Student:
def display(self):
print("Student details")
student1 = Student()
student1.display()
Class Method
- We use @classmethod.
class Student:
college = "ABC College"
@classmethod
def display_college(cls):
print(cls.college)
Student.display_college()
- Here cls refers to the class.
Static Method
- A static method does not require self or cls.
class Student:
@staticmethod
def message():
print("Welcome to Python OOP")
Student.message()
Top comments (0)