Python使用classmethod为多个构造函数

时间:2016-02-20 14:12:42

标签: python python-3.x

我一直在努力尝试使用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'

因为这是我能找到的唯一例子之一。

1 个答案:

答案 0 :(得分:1)

scala> var tup = ("TRN_KEY","88.330000;1;2") tup: (String, String) = (TRN_KEY,88.330000;1;2) scala> tup = tup.copy(_2 = tup._2 + "data") tup: (String, String) = (TRN_KEY,88.330000;1;2data) 应该有效:

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()