Contents
7.7. 类方法、静态方法、实例方法¶
方法包括:普通方法、静态方法和类方法,三种方法在内存中都归属于类,区别在于调用方式不同。
普通方法:由对象调用;至少一个self参数;执行普通方法时,自动将调用该方法的对象赋值给self;
类方法:由类调用; 至少一个cls参数;执行类方法时,自动将调用该方法的类复制给cls;
静态方法:由类调用;无默认参数;
普通方法
#!/usr/bin/env python
#-*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/13 17:34
# filename: class_space.py
class User:
name = "hujianli"
def walk(self):
print(self,"正在慢慢的行走")
#通过类调用实例方法
User.walk("hujianli")
hu = User()
User.walk(hu.name)
实例方法 eg
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/5/18 7:25
# filename: 实例方法test.py
class Animal(object):
'''
定义动物类
'''
def __init__(self, age, sex=1, weight=0.0):
# 定义实例变量
self.age = age
self.sex = sex
self.weight = weight
def eat(self):
"""
定义吃方法
:return:
"""
self.weight += 0.5
print("eat.......")
def run(self):
"""
定义跑方法
:return:
"""
self.weight -= 0.01
print("run......")
if __name__ == '__main__':
a1 = Animal(2, 0, 10.0)
print("a1体重:{0:0.2f}".format(a1.weight))
a1.eat()
print("a1体重:{0:0.2f}".format(a1.weight))
a1.run()
print("a1体重:{0:0.2f}".format(a1.weight))
输出结果:
a1体重:10.00
eat.......
a1体重:10.50
run......
a1体重:10.49
eg:
class Foo:
def __init__(self, name):
self.name = name
def ord_func(self):
""" 定义普通方法,至少有一个self参数 """
# print(self.name)
print('普通方法')
@classmethod
def class_func(cls):
""" 定义类方法,至少有一个cls参数 """
print('类方法')
@staticmethod
def static_func():
""" 定义静态方法 ,无默认参数"""
print ('静态方法')
# 调用普通方法
f = Foo()
f.ord_func()
# 调用类方法
Foo.class_func()
# 调用静态方法
Foo.static_func()
7.7.1. 用代码来理解¶
代码示例 1¶
#!/usr/bin/env python
#-*- coding:utf8 -*-
class Date():
#构造函数
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
#实例方法
def tomorrow(self):
self.day += 1
# 静态方法不用写self
@staticmethod
def parse_from_string(date_str):
year, month, day = tuple(date_str.split("-"))
# 静态方法不好的地方是采用硬编码,如果用类方法的话就不会了
return Date(int(year), int(month), int(day))
#类方法
@classmethod
def from_string(cls, date_str):
year, month, day = tuple(date_str.split("-"))
# cls:传进来的类,而不是像静态方法把类写死了
return cls(int(year), int(month), int(day))
def __str__(self):
return '%s/%s/%s'%(self.year,self.month,self.day)
if __name__ == "__main__":
new_day = Date(2018,5,9)
#实例方法
new_day.tomorrow()
print(new_day) #2018/5/10
#静态方法
date_str = '2018-05-09'
new_day = Date.parse_from_string(date_str)
print(new_day) #2018/5/9
# 类方法
date_str = '2018-05-09'
new_day = Date.from_string(date_str)
print(new_day) # 2018/5/9
代码示例 2¶
#!/usr/bin/env python
#-*- coding:utf8 -*-
"""
1.实例方法
2.类方法
3.静态方法
"""
#类中的方法都是实例方法
#定义静态方法需要用@staticmethod进行修饰
#定义类方法需要使用装饰器@classmethod进行修饰
class DemoMthd:
@staticmethod #静态方法不要传入self,类.方法名调用/实例名.方法名调用
def static_mthd():
print("调用静态方法!")
@classmethod
def class_mthd(cls):
print("调用了类方法!")
DemoMthd.static_mthd() # 未实例化,通过类名进行调用静态方法
DemoMthd.class_mthd() # 未实例化,通过类名调用类方法
print("".center(100,"*"))
print("实例化类之后,调用静态方法和类方法.")
hu = DemoMthd()
hu.static_mthd() #通过类实例调用静态方法
hu.class_mthd() #通过类实例调用类方法
eg
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/4/21 9:14
# filename: print_test.py
class Foo(object):
name = "类变量"
def __init__(self, name):
self.name = name
# 实例方法
def func(self):
print(self.name)
# 静态方法,如果方法中无需使用对象封装的值,可以使用静态方法
@staticmethod
def display():
'''
直接使用类名.方法名调用
也可以实例化后,实例名.方法名调用
:return:
'''
print("6666666")
@classmethod
def show(cls):
"""
类方法,参数为cls,调用时使用类名.方法名.
默认会将当前类传到参数中,
如果在方法中会使用到当前类,就可以使用类方法。
:return:
"""
print("类方法")
print("类方法调用:", cls.name)
if __name__ == '__main__':
obj = Foo("李雷和韩梅梅")
obj.func() # 实例方法
Foo.display() # 静态方法
Foo.show() # 类方法