不希望实例看到Python@classmethod

2024-04-27 00:55:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用@classmethod,但我不想用它污染实例的命名空间。如果我有一个类方法for_classes_only,如何防止实例获取它?你知道吗

class MyThing(object):
    def __init__(self, this=None):
        self.this = this

    @classmethod
    def for_classes_only(cls):
        print "I have a class {}".format(cls)


thing = MyThing(this='that')

这很好:

>>> MyThing.for_classes_only()
I have a class <class '__main__.MyThing'>

这很烦人:

>>> thing.for_classes_only
<bound method type.for_classes_only of <class '__main__.MyThing'>>

Tags: 实例selfonlyformaindefhavethis
1条回答
网友
1楼 · 发布于 2024-04-27 00:55:40

尝试使用metaclass

class Meta(type):
    # There is *NO* @classmethod decorator here
    def my_class_method(cls):
        print "I have a class {}".format(cls)

class MyThing(object):
    __metaclass__ = Meta
    def __init__(self, this=None):
        self.this = this

这是比大多数人需要或想要的更重的魔法,所以只有当你真的很确定你需要它的时候才这么做。大多数时候,一个正常的@classmethod就足够了。你知道吗

相关问题 更多 >