我一直在努力嘗試用classmethod裝飾器創建多個構造函數。有一個在SO一個例子 - What is a clean, pythonic way to have multiple constructors in Python?(第二個答案)python使用classmethod爲多個構造函數
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'
因爲這是我能找到的唯一例子之一。
你在期待'隨機(100)'做什麼?如果你導入'random'並用'random.randint(0,100)'代替調用,你的代碼工作正常。 –
我得到:'NameError:name'random'未定義'。 –
我期待'TypeError'是因爲'random'不需要參數或'NameError',如果你沒有導入'random'所以你的代碼不能產生那個錯誤信息 – styvane