静态方法和类方法
Python类包含三种方法:实例方法、静态方法和类方法。
说明:
实例方法只能被实例对象调用,静态方法(由@staticmethod装饰的方法)、类方法(由@classmethod装饰的方法),可以被类或类的实例对象调用。
实例方法,第一个参数必须要默认传实例对象,一般习惯用self。
静态方法,参数没有要求。
类方法,第一个参数必须要默认传类,一般习惯用cls。
其中,实例方法在前面的章节已经多次使用了。要想调用实例方法,必须要实例化类,然后才可以调用。也就是说,调用实例化方法需要类的实例(对象)。而静态方法在调用时根本不需要类的实例(静态方法不需要self参数),这一点和其他编程语言完全一样。
类方法的调用方式与静态方法完全一样,所不同的是,类方法与实例方法的定义方式相同,都需要一个self参数,只不过这个self参数的含义不同。
对于实例方法来说,这个self参数就代表当前类的实例,可以通过self访问对象中的方法和属性。而类方法的self参数表示类的元数据,也就是类本身,不能通过self参数访问对象中的方法和属性,只能通过这个self参数访问类的静态方法和静态属性。
定义静态方法需要使用@staticmethod装饰器(decorator)
定义类方法需要使用@classmethod装饰器。
“”"
静态方法和类方法
“”"
list = [
["00", "01", "02", "03", "04"],
["10", "11", "12", "13", "14"],
["20", "21", "22", "23", "24"],
["30", "31", "32", "33", "34"],
]
class Victor2:
def __init__(self,x,y):
self.x = x
self.y = y
# 定义一个静态变量,可以被静态方法和类方法访问
@staticmethod
def get_left():
return Victor2(0, -1)
@staticmethod
def get_right():
return Victor2(0,1)
@staticmethod
def get_up():
return Victor2(-1, 0)
class DoubleListhelper:
"""
二维列表助手类
"""
# 需求:30位置上获取3个元素
@staticmethod
def get_element(list_target, vect_pos, vect_dir, count):
list_result = []
for __ in range(count):
vect_pos.x += vect_dir.x
vect_pos.y += vect_dir.y
element = list_target[vect_pos.x][vect_pos.y]
list_result.append(element)
return list_result
#通过类的实例访问实例方法
pos = Victor2(2,1)
# 通过类访问类的静态变量
right = Victor2.get_right()
pos.x += right.x
pos.y += right.y
print(pos.x)
print(pos.y)
# 通过类访问类的静态变量
# 需求:20位置上向左获取3个元素
print(DoubleListhelper.get_element(list,Victor2(2,0), Victor2.get_left(),3))
# 需求:20位置上向右获取3个元素
print(DoubleListhelper.get_element(list,Victor2(2,0), Victor2.get_right(),3))
# 需求:20位置上向上获取3个元素
print(DoubleListhelper.get_element(list,Victor2(2,0), Victor2.get_up(),3))
输出结果:
2
2
['24', '23', '22']
['21', '22', '23']
['10', '00', '30']
从实例方法、静态方法和类方法的调用规则可以得出以下结论:
通过实例定义的变量只能被实例方法访问,而直接在类中定义的静态变量(如本例的name变量)即可以被实例方法访问,也可以被静态方法和类方法访问。实例方法不能被静态方法和类方法访问,但静态方法和类方法可以被实例方法访问。