Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Class method vs Static method trong Python

Class method trong Python là một phương thức, được ràng buộc với lớp chứ không phải đối tượng của lớp đó. Static method cũng tương tự nhưng có một số khác biệt cơ bản. Đối với class method, chúng ta cần chỉ định decorator @classmethod, và cho static method decorator @staticmethod được dùng.

Cú pháp cho Class Method:

class my_class:
    @classmethod
    def function_name(cls, arguments):
        # Function Body
        return value

Cú pháp cho Static Method:

class my_class:
    @staticmethod
    def function_name(arguments):
        # Function Body
        return value

Sự khác biệt giữa Classmethod và StaticMethod là gì?

Class Method Static Method
Class method nhận cls (class) làm đối số đầu tiên. Static method không nhận tham số cụ thể nào.
Class method có thể truy cập và sửa đổi trạng thái lớp. Static method không thể truy cập hoặc sửa đổi trạng thái lớp.
Class method nhận lớp làm tham số để biết trạng thái của lớp đó. Static method không biết về trạng thái lớp. Các phương thức này được dùng để làm một số tác vụ tiện ích bằng cách nhận một số tham số.
Decorator @classmethod được dùng ở đây. Decorator @staticmethod được dùng ở đây.

Các Static method được dùng để làm một số tác vụ tiện ích, và class method được dùng cho factory method. Các factory method có thể trả về đối tượng lớp cho các trường hợp sử dụng khác nhau.

Mã ví dụ

from datetime import date as dt

class Employee:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def isAdult(age):
        if age > 18:
            return True
        else:
            return False

    @classmethod
    def emp_from_year(emp_class, name, year):
        return emp_class(name, dt.today().year - year)

    def __str__(self):
        return 'Employee Name: {} and Age: {}'.format(self.name, self.age)

e1 = Employee('Dhiman', 25)
print(e1)
e2 = Employee.emp_from_year('Subhas', 1987)
print(e2)
print(Employee.isAdult(25))
print(Employee.isAdult(16))

Đầu ra

Employee Name: Dhiman and Age: 25
Employee Name: Subhas and Age: 31
True
False