普通方法类方法(@classmethod)静态方法(@staticmethod)
时间: 2023-10-09 09:16:45 浏览: 69
普通方法、类方法和静态方法是 Python 中的三种方法类型。
普通方法是最常见的方法类型,其第一个参数是 self,代表实例本身。普通方法可以访问实例的属性和方法。
类方法使用 @classmethod 装饰器来声明,其第一个参数是 cls,代表类本身。类方法可以访问类的属性和方法,但不能访问实例的属性和方法。
静态方法使用 @staticmethod 装饰器来声明,其没有默认的第一个参数,既不需要 cls,也不需要 self。静态方法不能访问类和实例的属性和方法,通常用于工具函数和辅助函数。
示例代码如下:
```python
class MyClass:
def instance_method(self):
print("This is an instance method")
@classmethod
def class_method(cls):
print("This is a class method")
@staticmethod
def static_method():
print("This is a static method")
```
使用示例:
```python
>>> obj = MyClass()
>>> obj.instance_method()
This is an instance method
>>> MyClass.class_method()
This is a class method
>>> MyClass.static_method()
This is a static method
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)