The @staticmethod Decorator
是用来写类里面的静态方法,在未创建对象的时候就可以使用这个方法,注意该方法没有self来传递实例对象的属性。
一个简单的使用例子:
class A:
def __init__(self, age: int) -> None:
self._age = age
@staticmethod
def isValid(age):
if age>18:
return True
else:
return False
print(A.isValid(20))
print(A.isValid(13))
a = A(20)
print(a.isValid(10))
长一点的例子:
from math import sqrt
class Triangle(object):
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
@staticmethod
def is_valid(a, b, c):
return a + b > c and b + c > a and a + c > b
def perimeter(self):
return self._a + self._b + self._c
def area(self):
half = self.perimeter() / 2
return sqrt(half * (half - self._a) *
(half - self._b) * (half - self._c))
def main():
a, b, c = 3, 4, 5
# 静态方法和类方法都是通过给类发消息来调用的
if Triangle.is_valid(a, b, c):
t = Triangle(a, b, c)
print(t.perimeter())
# 也可以通过给类发消息来调用对象方法但是要传入接收消息的对象作为参数
# print(Triangle.perimeter(t))
print(t.area())
# print(Triangle.area(t))
else:
print('无法构成三角形.')
if __name__ == '__main__':
main()
The @classmethod Decorator
也是用于修饰类的方法,它修饰的方法的第一个参数是cls,cls代表当前的对象的所有信息,它也可以在没有初始化对象的时候使用这个方法。
class B:
def __init__(self, firstname: str, secondname: str) -> None:
self._firstname = firstname
self._secondname = secondname
@classmethod
def init(cls, str_name):
firstname, secondname = str_name.split(' ')
student = cls(firstname, secondname)
return student
a = B.init("Albert Einstein")