2016-02-20 23 views
1

我一直在努力嘗試用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' 

因爲這是我能找到的唯一例子之一。

+1

你在期待'隨機(100)'做什麼?如果你導入'random'並用'random.randint(0,100)'代替調用,你的代碼工作正常。 –

+0

我得到:'NameError:name'random'未定義'。 –

+0

我期待'TypeError'是因爲'random'不需要參數或'NameError',如果你沒有導入'random'所以你的代碼不能產生那個錯誤信息 – styvane

回答

1

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 
+0

我仍然得到同樣的錯誤?如果您嘗試使用以下任一命令:emmentaler = Cheese.random()或leerdammer = Cheese.slightly_holey(),它不起作用 – VectorVictor

+0

只需將我的解決方案複製到新文件並從命令行運行即可。 –

+0

@VectorVictor目前還不清楚你做錯了什麼。此代碼有效。 – chepner