python-对象方法、静态方法、类方法

#-*- coding:utf-8 -*-

#本次学习:对象方法、静态方法、类方法

class SeniorTestingEngineer:
    #属性--只能对象来调用self.salary
    work_year=3
    salary=15000
    #行为 函数

    #self对象方法
    def coding(self,language,rows):#self(不能缺少)用来标记这个方法是对象方法,这个方法只能对象来调用
        print('{0}代码一级棒,一天写{1}行代码'.format(language,rows))
        print('工作年限是{0},月薪是{1}'.format(self.work_year,self.salary))#用对象来调用属性值

    @staticmethod#静态方法:是类中的函数,不需要特意创建对象来调用,当然也可以创建对象调用
    def do_mysql(name):
        print('数据库一级棒')
        # print('工作年限是{0},月薪是{1}'.format(self.work_year,self.salary))#静态方法无法调用属性值,因为没有对象,AttributeError: 'str' object has no attribute 'work_year'
          

    @classmethod#类方法
    def do_linux(cls):#传一个类名进来
        print('linux一级棒')
        print('工作年限是{0},月薪是{1}'.format(cls.work_year,cls.salary))#类方法必须用类名来调用属性值

    def do_auto_testing(self):
        print('自动化测试一级棒')



#对象方法
#1.对象方法 有 self
#2.对象方法可以通过对象self调用类里面的任意属性值
#3.只能由对象来调用

p1=SeniorTestingEngineer()#创建一个对象
p1.coding('python',500)



#静态方法
#1.静态方法 用 @staticmethod装饰
#2.静态方法无法调用属性值,所以不会涉及到类中的方法和属性的操作
#3.什么时候用静态方法:如果一个方法跟类里面的属性没有任何关联时使用静态方法
#4.支持对象和类名直接调用

SeniorTestingEngineer.do_mysql('')#静态方法,用类名.函数名调用
SeniorTestingEngineer().do_mysql('oracle')#静态方法,用对象.函数名调用

#类方法
#1.类方法 用@classmethod装饰
#2.类方法可以调用类中的属性,但是必须用类名来调用属性值
#3.支持对象和类名直接调用
SeniorTestingEngineer.do_linux()#类方法,支持用类名.函数名调用
SeniorTestingEngineer().do_linux()#类方法,支持用对象.函数名调用





原文地址:https://www.cnblogs.com/Aphrodite/p/10061366.html