通常,要使用类的方法,需要在调用方法之前实例化对象。
[En]
In general, to use a method of a class, you need to instantiate an object before calling the method.
而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
这有助于组织代码,将一些本应属于某个类的函数放入该类中,并有助于保持命名空间的整洁。
[En]
This helps to organize code, put some functions that should belong to a class into that class, and helps to keep the namespace clean.
因为@静态方法和@类方法都可以直接命名类。调用的方法名(),那么它们之间有什么区别呢?
[En]
Since both @ staticmethod and @ classmethod can directly name the class. Method name () to call, so what’s the difference between them?
从它们的使用情况来看,
[En]
Judging from their use,
- @staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
- *@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
如果要在@staticmethod中调用这个类的一些属性方法,只能直接调用类名。属性或类的名称。方法名称。
[En]
If you want to call some property methods of this class in @ staticmethod, you can only call the class name directly. The name of an attribute or class. Method name.
而@classmethod因为持有cls参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。
Original: https://www.cnblogs.com/timelesszhuang/p/8882904.html
Author: timelesszhuang
Title: python @staticmethod和@classmethod的作用
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/6557/
转载文章受原作者版权保护。转载请注明原作者出处!