Object methods, class methods, and static methods in Python

Object methods, class methods, and static methods in Python

1. Object method

The object-oriented method in the class , that is , the method whose default parameter is self , can only be called by the instantiated object, and the class name cannot be called. The sample program is as follows:

class Student:

    # 对象方法,只能被实例调用,不能被类调用
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 对象方法,只能被实例调用,不能被类调用
    def get_email(self):
        return self.name + str(self.age) +"@School.com"


stu1 = Student("Mike",12)       # 生成实例
print(stu1.get_email())         # 实例调用该方法
print(Student.get_email())      # 类名调用,会出错

Output result:
Output result

2. Class method

A class method is a method of a class, which can be called directly by the class name or by an instantiated object. The default parameter is cls , which means class . In a class , the modifier @ classmethod is usually added before the class method to indicate the class method. The sample program is as follows:

class Student:
    # 对象方法,只能被实例调用,不能被类调用
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 对象方法,只能被实例调用,不能被类调用
    def get_email(self):
        return self.name + str(self.age) +"@School.com"

    @classmethod  # 修饰器,被类调用,也可以被实例化对象调用
    def from_string(cls, stu_string):
        name, age = stu_string.split('-')
        return cls(name, age)

stu_string = "Jone-17"
stu2 = Student.from_string(stu_string) # 被类调用
print(stu2.get_email())

stu3 = Student("Mily",15)
stu3.from_string("Mili-16")   # 被实例化对象调用
print(stu3.get_email())

The output is as follows:
result

3. Static method

Static methods can be understood as ordinary methods or functions, which have no default parameters, and the modifier is @staticmethod . The sample program is as follows:

class Student:
    # 对象方法,只能被实例调用,不能被类调用
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 对象方法,只能被实例调用,不能被类调用
    def get_email(self):
        return self.name + str(self.age) +"@School.com"

    @classmethod  # 修饰器,被类调用,也可以被实例化对象调用
    def from_string(cls, stu_string):
        name, age = stu_string.split('-')
        return cls(name, age)

    @staticmethod
    def is_workday(day):
        if day.weekday() == 5 or day.weekday == 6:
            return False
        return True
from datetime import datetime
day = datetime(2020,8,3)
print(Student.is_workday(day))

The output is:

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45727931/article/details/107780993