Python类中普通方法、类方法与静态方法的用法详解
本文详细解析Python类中的三种核心方法:普通方法、类方法和静态方法。通过Student类的具体代码示例,演示如何定义实例总分计算的普通方法、利用字符串创建实例的类方法(@classmethod),以及判断工作日期的静态方法(@staticmethod)。文章涵盖运行环境配置及完整代码实现,帮助开发者掌握不同方法的适用场景与调用方式。
前言
本文重点介绍Python类中常用的三种方法类型:普通方法、类方法和静态方法。内容主要参考自视频系列https://youtu.be/rq8cL2XMM5M,强烈建议读者观看该系列完整视频以获取更深入的理解。
运行环境
import sys
sys.version
测试结果如下所示:
'3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]'
普通方法
首先定义一个名为Student的类,并在其中创建一个普通方法total_score(),该方法用于计算并返回特定学生实例的总分。
class Student(object):
num_of_stu = 0 #学生人数
def __init__(self, name, age, math, Chinese):
self.name = name #学生姓名
self.age = age #学生年龄
self.math = math #数学成绩
self.Chinese = Chinese #语文成绩
Student.num_of_stu += 1 #每实例化一个学生,人数加1,相当于静态变量
def __del__(self):
Student.num_of_stu -= 1 #每删除一个实例,人数减1
#普通方法,用于计算学生的总分
def total_score(self):
return self.math + self.Chinese
接下来,我们创建几个Student实例进行测试。
print (Student.num_of_stu)
stu1 = Student('Bob', 11, 51, 33)
print (stu1.total_score())
stu2 = Student('Peco', 12, 98, 79)
print (stu2.total_score())
print (Student.num_of_stu)
del stu1
print (Student.num_of_stu)
运行结果如下:
0 84 177 2 1
类方法
假设我们需要通过一个字符串格式的数据来创建Student实例,此时可以使用类方法from_string来实现这一功能。
class Student(object):
num_of_stu = 0 #学生人数
def __init__(self, name, age, math, Chinese):
self.name = name #学生姓名
self.age = age #学生年龄
self.math = math #数学成绩
self.Chinese = Chinese #语文成绩
Student.num_of_stu += 1 #每实例化一个学生,人数加1,相当于静态变量
def __del__(self):
Student.num_of_stu -= 1 #每删除一个实例,人数减1
#普通方法,用于计算学生的总分
def total_score(self):
return self.math + self.Chinese
#类方法,用于用字符串生成实例
@classmethod
def from_string(cls, stu_str):
name, age, math, Chinese = stu_str.split('-')
return cls(name, int(age), float(math), float(Chinese))
我们进行实际测试。
stu_str = "Bob-12-50-34"
stu1 = Student.from_string(stu_str)
print (stu1.name, stu1.total_score())
输出结果为:
Bob 84.0
静态方法
若需判断某天是否为上课日,可以在类中定义一个静态方法来实现此逻辑。
class Student(object):
num_of_stu = 0 #学生人数
def __init__(self, name, age, math, Chinese):
self.name = name #学生姓名
self.age = age #学生年龄
self.math = math #数学成绩
self.Chinese = Chinese #语文成绩
Student.num_of_stu += 1 #每实例化一个学生,人数加1,相当于静态变量
def __del__(self):
Student.num_of_stu -= 1 #每删除一个实例,人数减1
#普通方法,用于计算学生的总分
def total_score(self):
return self.math + self.Chinese
#类方法,用于用字符串生成实例
@classmethod
def from_string(cls, stu_str):
name, age, math, Chinese = stu_str.split('-')
return cls(name, int(age), float(math), float(Chinese))
#静态方法,用于判断要不要上学
@staticmethod
def is_school_day(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
我们进行相应测试。
import datetime
my_date1 = datetime.date(2017, 9, 15)
my_date2 = datetime.date(2017, 9, 16)
print (Student.is_school_day(my_date1))
print (Student.is_school_day(my_date2))
输出结果为:
True False
以上是对Python普通方法、类方法及静态方法的详细示例解析,更多关于Python方法的高级用法,请参阅本站其他相关文章。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













