1 '''
2 静态方法(Static Methods)是定义在类中的普通方法,与类和实例对象没有直接关联。静态方法可以通过类名直接调用,也可以通过实例对象调用。
3
4 1. 定义静态方法:
5 1. 静态方法使用@staticmethod装饰器来标识。
6 2. 静态方法不需要传递类或实例参数。
7 3. 静态方法无法访问类属性、实例属性和其他类方法。
8
9 2. 最佳实践:
10 1. 静态方法适合用于不依赖于类或实例状态的操作。
11 2. 静态方法通常用于实现辅助函数或独立的功能。
12
13 3. 使用场景:
14 1. 执行与类或实例无关的计算或操作时,可以使用静态方法。
15 2. 实现工具函数、辅助函数或独立的功能时,静态方法很有用。
16 3. 在无需类属性或实例属性的情况下,可以使用静态方法。
17
18 4. 坑:
19 1. 静态方法无法直接访问类属性、实例属性和其他类方法。
20 2. 由于静态方法与类和实例对象没有直接关联,因此在静态方法中无法直接访问这些成员。
21 '''
22
23
24 # 1. 语法
25 class MyClass:
26 @staticmethod
27 def static_method():
28 print("This is a static method")
29
30
31 # 调用静态方法
32 MyClass.static_method() # This is a static method
33
34 # 2. 最佳实践
35 import math
36
37
38 class Geometry:
39 @staticmethod
40 def calculate_area(radius):
41 return math.pi * radius ** 2
42
43
44 # 调用静态方法
45 area = Geometry.calculate_area(5)
46 print(area) # 78.53981633974483
47
48
49 # 4. 坑
50 class MyClass:
51 class_attribute = "This is a class attribute"
52
53 @staticmethod
54 def static_method():
55 print(MyClass.class_attribute) # This is a class attribute,无法直接访问类属性,但可以通过类名.类属性访问
56 # test() # 这样不行
57 # print(class_attribute) # 这样也不行
58 def test(self):
59 print('test')
60
61
62 # 调用静态方法
63 MyClass.static_method() # This is a class attribute