Python类方法的示例用例是什么?

2024-10-06 12:21:35 发布

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

我读过What are Class methods in Python for?,但那篇文章中的例子很复杂。我正在寻找一个清晰、简单、简单的例子来说明Python中类方法的特定用例。

您能举出一个小的、特定的示例用例吗?在这个用例中,Python类方法将是该工作的正确工具?


Tags: 工具方法in示例for用例whatare
3条回答

初始化的帮助程序方法:

class MyStream(object):

    @classmethod
    def from_file(cls, filepath, ignore_comments=False):    
        with open(filepath, 'r') as fileobj:
            for obj in cls(fileobj, ignore_comments):
                yield obj

    @classmethod
    def from_socket(cls, socket, ignore_comments=False):
        raise NotImplemented # Placeholder until implemented

    def __init__(self, iterable, ignore_comments=False):
       ...

是一个非常重要的类方法。它是实例通常来自的地方

所以dict()调用dict.__new__当然,但有时还有另一种方便的方法来生成dict,那就是classmethod dict.fromkeys()

例如

>>> dict.fromkeys("12345")
{'1': None, '3': None, '2': None, '5': None, '4': None}

我不知道,类似于命名构造函数的方法?

class UniqueIdentifier(object):

    value = 0

    def __init__(self, name):
        self.name = name

    @classmethod
    def produce(cls):
        instance = cls(cls.value)
        cls.value += 1
        return instance

class FunkyUniqueIdentifier(UniqueIdentifier):

    @classmethod
    def produce(cls):
        instance = super(FunkyUniqueIdentifier, cls).produce()
        instance.name = "Funky %s" % instance.name
        return instance

用法:

>>> x = UniqueIdentifier.produce()
>>> y = FunkyUniqueIdentifier.produce()
>>> x.name
0
>>> y.name
Funky 1

相关问题 更多 >