我一直在努力尝试使用classmethod装饰器创建多个构造函数。 SO中有一个示例-What is a clean, pythonic way to have multiple constructors in Python?(第二个答案)
class Cheese(object):
def __init__(self, num_holes=0):
"defaults to a solid cheese"
self.number_of_holes = num_holes
@classmethod
def random(cls):
return cls(random(100))
@classmethod
def slightly_holey(cls):
return cls(random(33))
@classmethod
def very_holey(cls):
return cls(random(66, 100))
但是这个例子不是很清楚,在键入命令时,代码在Python 3中对我不起作用:
gouda = Cheese()
emmentaler = Cheese.random()
leerdammer = Cheese.slightly_holey()
给予-
AttributeError: type object 'Cheese' has no attribute 'random'
因为这是我能找到的仅有的例子之一。
最佳答案
randint
应该可以工作:
from random import randint
class Cheese(object):
def __init__(self, num_holes=0):
"defaults to a solid cheese"
self.number_of_holes = num_holes
@classmethod
def random(cls):
return cls(randint(0, 100))
@classmethod
def slightly_holey(cls):
return cls(randint(0, 33))
@classmethod
def very_holey(cls):
return cls(randint(66, 100))
gouda = Cheese()
emmentaler = Cheese.random()
leerdammer = Cheese.slightly_holey()
现在:
>>> leerdammer.number_of_holes
11
>>> gouda.number_of_holes
0
>>> emmentaler.number_of_holes
95