DEV Community

Punitha
Punitha

Posted on

Attributes and Methods

  • 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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Class Method

  • We use @classmethod.
class Student:

    college = "ABC College"

    @classmethod
    def display_college(cls):
        print(cls.college)

Student.display_college()
Enter fullscreen mode Exit fullscreen mode
  • 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()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)