浅聊Python class中的@staticmethod以及@classmethod

前言

入学不久以后,我就在想,对于学校的这么多人,这么多教师,这么多学生,以及其余种种事物,可否对应的作一套"系统"下来呢?
随之也跟着思考了起来。测试

设计

好了,最直观的映入大脑的就是三个实体:
教师学生
这三个实体分别有对应的feature属性以表示其为人/教师/学生。
由此,获得如下三个class。设计

class Person():

    FEATURE = 'P'    

    def __init__(self):
        pass


class Teacher(Person):

    FEATURE = 'T'
    
    def __init__(self):
        pass
        
        
class Student(Person):

    FEATURE = 'S'    

    def __init__(self):
        pass

然而,做为学生表明的我,绝对不容许老师混入进来充当间谍。因此,必须给学生类提供一个方法以判断是否为学生。那么,对于这个方法,仅须要从Student类去调用便可,并不是必定须要实例化的对象。并且,该方法由Student所独享,Teacher并不须要判断是否为学生。由此,Student改进为如下版本。code

class Student(Person):

    FEATURE = 'S'    

    def __init__(self):
        pass

    @staticmethod
    def is_student(obj):
        if obj.FEATURE == 'S':            
            return True
        else:
            return False

正在思考的时候,一位代课老师过来看到了个人大概设计,而后说,“同窗啊,你介个设计呢,对于咱们老师,少了点东西,做为老师,咱们有分文理,文理以后还有数学...blah..blah..”。
而后我就走神了,对啊,老师还根据教学科目分文理呢,有数学老师,有音乐老师,有...对象

class MathTeacher(Teacher):

    TEACHING = 'MATH'
    
    def __init__(self):
        pass

class DrawingTeacher(Teacher):

    TEACHING = 'DRAWING'
    
    def __init__(self):
        pass

因此以上为表明的两个类就诞生了。至于对于文理的判断,短暂的思考以后,决定把该功能添加到Teacher类作以判断。ci

class Teacher(Person):

    FEATURE = 'T'
    
    def __init__(self):
        pass

    @classmethod
    def category(cls):

        science_cate = ['MATH']
        arts_cate = ['DRAWING', 'PAINTING']

        teaching = getattr(cls, 'TEACHING', None)

        if teaching in science_cate:
            return 'Science'
        elif teaching in arts_cate:
            return 'Arts'
        else:
            return 'Unknow'

测试

在完成以上初步构想以后,决定测试一下所写代码是否能按预期执行。
获得以下测试代码get

p = Person()
t = Teacher()
s = Student()

print(Student.is_student(p))    #False
print(Student.is_student(t))    #False
print(Student.is_student(s))    #True

而对于教学分类的判断,则有如下两种情形。数学

  • 判断某个教师 属于哪一个教学分类it

print(DrawingTeacher.category())    #Arts
print(MathTeacher.category())       #Science
print(Teacher.category())           #Unknow
  • 判断某个教师 实例 属于哪一个教学分类class

teacher_wang = DrawingTeacher()
teacher_li = MathTeacher()
teacher = Teacher()

print(teacher_wang.category())    #Arts
print(teacher_li.category())      #Science
print(teacher.category())         #Unknow

结束

到此时,再回过头一看,噗,什么狗屁设计。方法

相关文章
相关标签/搜索