我读过What are Class methods in Python for?,但那篇文章中的例子很复杂。我正在寻找一个清晰、简单的Python类方法特定用例的基本示例。
你能举出一个小的,具体的示例用例,其中Python类方法将是适合这项工作的工具?
发布于 2011-04-21 09:40:47
初始化的帮助器方法:
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):
...
发布于 2011-04-21 09:48:27
__new__
是一个非常重要的类方法。它是实例通常来自的地方
所以dict()
当然会调用dict.__new__
,但有时还有另一种方便的方法来编写字典,那就是类方法dict.fromkeys()
例如:
>>> dict.fromkeys("12345")
{'1': None, '3': None, '2': None, '5': None, '4': None}
发布于 2011-04-21 09:33:50
我不知道,比如命名构造函数方法?
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
https://stackoverflow.com/questions/5738470
复制相似问题