python - @staticmethods 在 @classmethod 期间调用

标签 python python-3.x

使用@classmethod时有没有办法调用@staticmethod

@dataclass 
class Piza:
    ingridients: List

    @classmethod
    def make_Pizza(cls, ingrid, allerg=False):
        ingridients = ingrid
        if allerg:
            return cls(make_for_allerg(ingrid, allerg))
        return cls(ingrid)

    @staticmethod
    def make_for_allerg(ingrid, allerg):
        return ingrid.append(allerg)

测试没有过敏:

Piza.make_Pizza(['tomato', 'cheese'])

Piza(ingridients=['tomato', 'cheese'])

过敏测试错误:

Piza.make_Pizza(['tomato', 'cheese'], allerg='pickle')

--------------------------------------------------------------------------- NameError Traceback (most recent call last) in () 1 ----> 2 Piiza.make_Piza(['tomato', 'cheese'], allerg='pickle')

in make_Pizza(cls, ingrid, allerg) 7 ingridients = ingrid 8 if allerg: ----> 9 return cls(make_for_allerg(ingrid, allerg)) 10 return cls(ingrid) 11

NameError: name 'make_for_allerg' is not defined

最佳答案

staticmethod 是类对象的一个​​属性,因此它仍然由类名命名。您可以在类对象上调用它:

Piza.make_for_allerg(...)

注意:您的实现对于静态方法来说不是一个令人信服的用例。 list.append 的返回值始终为 None

关于python - @staticmethods 在 @classmethod 期间调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52188574/

相关文章:

python-3.x - Airflow:使用 MySqlHook 获取连接

python - 使用 BeautifulSoup 提取 <script> 的内容

python - 使用python从网络摄像头修剪(删除帧)实时视频

python - 在 pygame 中暂停游戏和用户输入

python - 词性标注——NLTK 认为名词是形容词

python - 如何编写代码来获取 python 列表中每个列表的最低值?

python - 如何在 python 中找到 csv 文件的一列的平均值?

python 3 : Comparing multiple dictionaries in a list/Deleting repeated entries

python - 如何删除 Tkinter OptionMenu 小部件的边框

python - 如何从 qtreeWidgetItem 中获取comboBox.currentText() 和 SpinBox.text()