jjzjj

staticMethod

全部标签

python - 为什么@staticmethod 没有跨类保留,而@classmethod 是?

以下面的示例脚本为例:classA(object):@classmethoddefone(cls):print("Iamclass")@staticmethoddeftwo():print("Iamstatic")classB(object):one=A.onetwo=A.twoB.one()B.two()当我使用Python2.7.11运行此脚本时,我得到:IamclassTraceback(mostrecentcalllast):File"test.py",line17,inB.two()TypeError:unboundmethodtwo()mustbecalledwithBin

python - 为什么使用 classmethod 而不是 staticmethod?

这个问题在这里已经有了答案:Differencebetween@staticmethodand@classmethod(34个回答)关闭9年前。我知道他们在做什么,并且我已经看过很多这两种方法的例子,但我还没有找到一个我必须使用classmethod而不是用替换它的例子静态方法.我见过的classmethod最常见的例子是为类本身创建一个新实例,像这样(非常简单的例子,没有使用方法atm。但你明白了):classFoo:@classmethoddefcreate_new(cls):returncls()这将在调用foo=Foo.create_new()时返回一个新的Foo实例。现在为什

python - “staticmethod”对象不可调用

我有这个代码:classA(object):@staticmethoddefopen():return123@staticmethoddefproccess():return456switch={1:open,2:proccess,}obj=A.switch[1]()当我运行它时,我不断收到错误:TypeError:'staticmethod'objectisnotcallable如何解决? 最佳答案 您将unboundstaticmethod对象存储在字典中。此类对象(以及classmethod对象、函数和property对象)仅

python - @classmethod 和 @staticmethod 对初学者的意义

这个问题在这里已经有了答案:Differencebetween@staticmethodand@classmethod(34个回答)关闭3年前.@classmethod和@staticmethod在Python中是什么意思,它们有何不同?什么时候我应该使用它们,为什么我应该使用它们,我应该如何使用它们?据我了解,@classmethod告诉一个类它是一个应该被继承到子类中的方法,或者......什么。然而,这有什么意义呢?为什么不直接定义类方法而不添加@classmethod或@staticmethod或任何@定义? 最佳答案 虽然

python - @staticmethod 和 @classmethod 之间的区别

用@staticmethod修饰的函数有什么区别?一个用@classmethod装饰? 最佳答案 也许一些示例代码会有所帮助:注意foo、class_foo和static_foo的调用签名的区别:classA(object):deffoo(self,x):print(f"executingfoo({self},{x})")@classmethoddefclass_foo(cls,x):print(f"executingclass_foo({cls},{x})")@staticmethoddefstatic_foo(x):print(

python - 在类体内调用类静态方法?

当我尝试从类的主体中使用静态方法,并使用内置的staticmethod函数作为装饰器定义静态方法时,如下所示:classKlass(object):@staticmethod#useasdecoratordef_stat_func():return42_ANS=_stat_func()#callthestaticmethoddefmethod(self):ret=Klass._stat_func()+Klass._ANSreturnret我收到以下错误:Traceback(mostrecentcalllast):File"call_staticmethod.py",line1,incl

python - 在类体内调用类静态方法?

当我尝试从类的主体中使用静态方法,并使用内置的staticmethod函数作为装饰器定义静态方法时,如下所示:classKlass(object):@staticmethod#useasdecoratordef_stat_func():return42_ANS=_stat_func()#callthestaticmethoddefmethod(self):ret=Klass._stat_func()+Klass._ANSreturnret我收到以下错误:Traceback(mostrecentcalllast):File"call_staticmethod.py",line1,incl