码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-12-03 23:01:11      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:方法   coding   关联   icm   linux   png   pytho   自动化测试   必须   

#-*- 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()#类方法,支持用对象.函数名调用




技术分享图片

 

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

标签:方法   coding   关联   icm   linux   png   pytho   自动化测试   必须   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!