python面向对象编程中类方法和静态方法是怎样的
本篇文章给大家分享的是有关python面向对象编程中类方法和静态方法是怎样的,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

成都创新互联是一家集网站建设,德化企业网站建设,德化品牌网站建设,网站定制,德化网站建设报价,网络营销,网络优化,德化网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
今天学习python的面向对象编程-类方法和静态方法。
新建一个python文件命名为py3_oop3.py,在这个文件中进行操作代码编写:
#面向对象编程#类方法和静态方法class Employee:raise_amount = 1.04#定义类变量num_of_emps = 0def __init__(self,first,last,pay):self.first = firstself.last = lastself.email = first + '.' + last +'@email.com'self.pay = payEmployee.num_of_emps +=1def fullname(self):return '{} {}'.format(self.first,self.last)def apply_raise(self):self.pay = int(self.pay * self.raise_amount)#类方法用@classmethod标识符修饰#cls作为第一个参数用来表示类本身.#在类方法中用到,类方法是只与类本身有关#而与实例无关的方法@classmethoddef set_raise_amt(cls,amount):cls.raise_amount = amount#定义一个接收emp String#返回实例化对象的类方法@classmethoddef from_emp_str(cls,emp_str):first,last,pay = emp_str.split('-')#这里理解为调用#Employee(first,last,pay)#并返回return cls(first,last,pay)#静态方法用@staticmethod标识符修饰#就像一个普通的函数#判断是不是工作日@staticmethoddef is_workday(day):if day == 5 or day ==6:return Falsereturn Trueemp_1 = Employee('T','Bag',50000)emp_2 = Employee('Mc','User',6000)Employee.set_raise_amt(1.05)print(Employee.raise_amount)#1.05print(emp_1.raise_amount)#1.05print(emp_2.raise_amount)#1.05#我们调用emp_1.set_raise_amt()#在打印Employee.set_raise_amt(1.06)print(Employee.raise_amount)#1.06print(emp_1.raise_amount)#1.06print(emp_2.raise_amount)#1.06#发现类和实例对象的raise_amount全部跟着改变#我们打印emp_1的属性信息print(emp_1.__dict__)#{'first': 'T', 'last': 'Bag', 'email': 'T.Bag@email.com','pay': 50000}#这里并不包含raise_amount属性#因为调用类方法set_raise_amt#修改的是类的变量属性#定义一个emp string#调用from_emp_str()emp_str = 'T-Bag-5000'new_emp_1 = Employee.from_emp_str(emp_str)print(new_emp_1.email)#T.Bag@email.com#调用类Employee静态方法:import datetimetoday = datetime.datetime.today()print(Employee.is_workday(today))#True
运行结果:
1.051.051.051.061.061.06{'first': 'T', 'last': 'Bag', 'email': 'T.Bag@email.com', 'pay': 50000}T.Bag@email.comTrue 以上就是python面向对象编程中类方法和静态方法是怎样的,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。
本文标题:python面向对象编程中类方法和静态方法是怎样的
浏览路径:http://www.jxjierui.cn/article/godehg.html


咨询
建站咨询
