【问题标题】:Can't call static method inside class不能在类中调用静态方法
【发布时间】:2023-04-11 10:39:02
【问题描述】:

这就是我想要做的 在类中调用静态方法来填充类变量。

import sys
import os
from HelpingData import *

class Inventory(object):
    shipping_cost = 400.0   
    total_stock = calculate_total_stock.__func__()

    def __init__(self, attributes={}):
        self.inventory = {}
        if attributes is None:
             self.inventory = {}
        else:    
             for key in attributes:
                self.inventory[key] = attributes[key]  


    def getValue(self,attribute):
        return self.inventory[attribute]  


    def setValue(self,attribute,value):
        self.inventory[attribute]=value 

    @staticmethod        
    def calculate_total_stock():
       total_stock = dict((item, 0) for item in product_names)
       for nation in product_stock:
           for item in nation:
              total_stock[item] += nation[item]
       return total_stock   

这是我得到的错误..

>   total_stock = calculate_total_stock.__func__() 
    NameError: name'calculate_total_stock' is not defined

有人可以建议我吗,我在这里缺少什么,我是 python 新手。 1 天大

【问题讨论】:

  • 请检查您的缩进并提供一个复制错误的minimal example。但是请注意,您不能在定义之前调用calculate_total_stock
  • 缩进就好了。我只给出了最少的代码。
  • 请原谅我的编辑,当我在这里发布时格式发生了变化,在我的代码中缩进是正确的..
  • 请检查代码,现在告诉我你看到了什么错误
  • 预注释,调用前移动函数声明没有帮助,错误来了,库存未定义..(即)类名

标签: python error-handling static-methods


【解决方案1】:

这里你真的不需要任何解决方法,只需给调用方法一个额外的方向。

在下面的示例中,您可以在其定义类的内部和外部调用 PrintThis() 方法。

外部:

像往常一样打电话

  • MyClass.PrintThis('42')

内部:

您必须添加 self 或包含的类

  • MyClass.PrintThis('42')
  • self.PrintThis('42')

产生错误:

class MyClass:

    def __init__(self):
        self.MyValue = 0

    def IncrementValue(self):
        self.MyValue += 1
    
        PrintThis(f'From MyClass {self.MyValue}')

    @staticmethod
    def PrintThis(arg):
        print(f'My Value: {arg}')

    

修复:

class MyClass:

    def __init__(self):
        self.MyValue = 0

    def IncrementValue(self):
        self.MyValue += 1
        self.PrintThis(f'From MyClass {self.MyValue}')

    @staticmethod
    def PrintThis(arg):
        print(f'My Value: {arg}')

运行它

    class Run:
        def __init__(self):
        
            mc = MyClass()

            MyClass.PrintThis('From Outside')

            mc.IncrementValue()
            mc.IncrementValue()



My Value: From Outside
My Value: From MyClass 1
My Value: From MyClass 2

为什么?

我不确定:-)

我唯一注意到的是静态方法(PrintThis)是一个函数,而非静态方法是一个绑定方法。

我确信 Python 文档中对此行为有一些解释。如果您查找,请分享:-)

我知道这个问题在这一点上已经有几年的历史了,但是当我用谷歌搜索故障时,这是第一个命中。

【讨论】:

    【解决方案2】:

    Inventory 定义的顶层代码(即类属性和方法定义)在名称 Inventory 存在之前运行,因此您不能在定义。既然你有一个@staticmethod,它不需要任何类或实例参数,为什么不把它移到外面呢?

    def calculate_total_stock(product_names, product_stock):
        total_stock = dict((item, 0) for item in product_names)
        for nation in product_stock:
            for item in nation:
               total_stock[item] += nation[item]
        return total_stock
    
    
    class Inventory(object):
    
        SHIPPING_COST = 400.0   
        TOTAL_STOCK = calculate_total_stock(product_names, product_stock)
    
        def __init__(self, attributes=None):
            self.inventory = {}
            if attributes is not None:
                for key in attributes:
                    self.inventory[key] = attributes[key]  
    
        def get_value(self, attribute):
            return self.inventory[attribute]  
    
        def set_value(self, attribute, value):
            self.inventory[attribute] = value 
    

    请注意,我已经进行了一些整理,尤其是在 style 方面,并为 calculate_total_stock 提供了明确的参数。

    【讨论】:

    • 我做了同样的事情,错误来了:未定义库存(即类名)
    • 是的,解决方法总是可能的,我只是想不通,为什么以前的代码不起作用,当类名出现名称错误时。 PS。感谢您的努力
    • 我在回答开始时已经解释过了
    猜你喜欢
    • 2013-06-09
    • 2023-02-22
    • 2011-01-13
    • 2017-11-27
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    相关资源
    最近更新 更多