python面向对象编程中类方法和静态方法是怎样的

发布时间:2021-12-04 09:21:33 作者:柒染
来源:亿速云 阅读:104

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

今天学习python的面向对象编程-类方法和静态方法。

新建一个python文件命名为py3_oop3.py,在这个文件中进行操作代码编写:

#面向对象编程#类方法和静态方法
class Employee:  raise_amount = 1.04#定义类变量  num_of_emps = 0  def __init__(self,first,last,pay):    self.first = first    self.last = last    self.email = first + '.' + last +'@email.com'    self.pay = pay    Employee.num_of_emps +=1
 def fullname(self):    return '{} {}'.format(self.first,self.last)
 def apply_raise(self):    self.pay = int(self.pay * self.raise_amount)  #类方法用@classmethod标识符修饰    #cls作为第一个参数用来表示类本身.  #在类方法中用到,类方法是只与类本身有关  #而与实例无关的方法  @classmethod    def set_raise_amt(cls,amount):    cls.raise_amount = amount  #定义一个接收emp String  #返回实例化对象的类方法  @classmethod  def from_emp_str(cls,emp_str):    first,last,pay = emp_str.split('-')    #这里理解为调用    #Employee(first,last,pay)    #并返回    return cls(first,last,pay)    #静态方法用@staticmethod标识符修饰  #就像一个普通的函数  #判断是不是工作日  @staticmethod    def is_workday(day):    if day == 5 or day ==6:      return False    return True
emp_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面向对象编程中类方法和静态方法是怎样的,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. python:静态方法、类方法、属性方法
  2. Python 静态方法和类方法实例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:如何借助HTTP通过SSH绕过Linux防火墙

下一篇:网页里段落的html标签是哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》