装饰的功能@staticmethod和装饰的功能有什么区别@classmethod?
这个问题不是讨论单身人士设计模式是否可取,反模式,还是任何宗教战争,而是讨论如何以最蟒蛇的方式在Python中最好地实现这种模式.在这种情况下,我将"最pythonic"定义为表示它遵循"最小惊讶原则".
我有多个类可以成为单例(我的用例是记录器,但这并不重要).当我可以简单地继承或装饰时,我不希望在添加gumph的几个类中混乱.
最好的方法:
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class MyClass(BaseClass):
pass
Run Code Online (Sandbox Code Playgroud)
优点
缺点
m = MyClass(); n = MyClass(); o = type(n)();那时m == n && m != o && n != oclass Singleton(object):
_instance = None
def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance
class MyClass(Singleton, …Run Code Online (Sandbox Code Playgroud) 我认为以下代码会导致错误,因为据我所知,Python 类中的方法必须将“self”(或任何其他标签,但按照约定是“self”)作为其第一个参数,或者如果使用了@classmethod装饰器,则为“cls”或类似名称,如果使用了装饰器,则为 none @staticmethod。
为什么我在终端中使用 Python 3.5 运行它没有错误,即使test_method不满足这些要求?它似乎作为静态方法工作正常,但没有装饰器。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
class MyClass:
def test_method(args):
print(args[1])
@staticmethod
def static_method():
print("static_method")
@classmethod
def class_method(cls):
print("class_method")
def main(args):
MyClass.test_method(args)
if __name__ == '__main__':
sys.exit(main(sys.argv))
Run Code Online (Sandbox Code Playgroud)
输出:
$ python3 testscript.py "testing"
$ testing
Run Code Online (Sandbox Code Playgroud)
编辑:
我的问题也可以用不同的措辞,将注意力从self和转移到@staticmethod:“我怎么会在没有 @staticmethod 装饰器的情况下得到一个看似有效的静态方法?”
python ×3
methods ×2
base-class ×1
class ×1
class-method ×1
decorator ×1
metaclass ×1
oop ×1
singleton ×1