Python对多个构造函数使用classmethod

2024-10-01 17:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力用classmethoddecorator创建多个构造函数。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'

因为这是我能找到的唯一的例子之一。你知道吗


Tags: toselfreturnobjectdefrandomnum例子
1条回答
网友
1楼 · 发布于 2024-10-01 17:27:57

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

相关问题 更多 >

    热门问题