Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Class method เทียบ Static method ใน Python

Class method ใน Python คือเมธอดที่ผูกกับคลาส แต่ไม่ใช่ออบเจ็กต์ของคลาสนั้น Static methods เหมือนกันแต่มีความแตกต่างพื้นฐานบางอย่าง สำหรับ class methods ต้องระบุ @classmethod decorator และสำหรับ static method ใช้ @staticmethod decorator

Syntax สำหรับ Class Method:

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

Syntax สำหรับ Static Method:

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

ความแตกต่างระหว่าง Classmethod และ StaticMethod

Class Method Static Method
Class method รับ cls (class) เป็นอาร์กิวเมนต์แรก Static method ไม่รับพารามิเตอร์เฉพาะเจาะจง
Class method เข้าถึงและแก้ไข class state ได้ Static Method เข้าถึงหรือแก้ไข class state ไม่ได้
Class method รับ class เป็นพารามิเตอร์เพื่อรู้ state ของคลาสนั้น Static methods ไม่รู้ class state ใช้ทำ utility tasks โดยรับพารามิเตอร์บางอย่าง
ใช้ @classmethod decorator ใช้ @staticmethod decorator

Static methods ใช้ทำ utility tasks และ class methods ใช้สำหรับ factory methods Factory methods สามารถคืนค่า class objects สำหรับ use cases ต่างๆ ได้

ตัวอย่างโค้ด

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))

ผลลัพธ์

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