简体   繁体   English

不能在类内部调用静态方法

[英]Can't call static method inside class

This is what i am trying to do call a static method inside a class to populate the class variable.这就是我试图在类中调用静态方法来填充类变量的方法。

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   

And this is the error i am getting..这是我得到的错误..

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

Can someone suggest me, what i am missing here, i am new to python.有人可以建议我,我在这里缺少什么,我是python的新手。 1 day old 1天大

The code at the top level of the Inventory definition (ie class attributes and method definitions) runs before the name Inventory exists, so you can't call its own methods within the definition. Inventory定义顶层的代码(即类属性和方法定义)名称Inventory存在之前运行,因此您不能在定义中调用它自己的方法。 As you have a @staticmethod , which doesn't require any class or instance argument, why not move it outside?由于您有一个不需要任何类或实例参数的@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 

Note that I have done some tidying up, particularly in terms of style and making the explicit arguments to calculate_total_stock .请注意,我已经做了一些整理工作,特别是在样式方面以及为calculate_total_stock制定了明确的参数。

You really don't need any workaround here, just give the calling method an additional level of direction.您在这里真的不需要任何解决方法,只需为调用方法提供额外的指导。

In the example below you can call the PrintThis() method both internal and external to its defining class.在下面的示例中,您可以在其定义类的内部和外部调用 PrintThis() 方法。

External:外部的:

Call as you normally would像往常一样打电话

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

Internal:内部的:

You must add self or the containing class您必须添加 self 或包含类

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

To produce the error:产生错误:

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}')

    

The Fix:修复:

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}')

Run It运行

    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

Why?为什么?

I'm not sure :-)我不知道 :-)

The only thing I noticed is that the static method (PrintThis) is a function, while the non-static method is a bound method.我唯一注意到的是静态方法(PrintThis)是一个函数,而非静态方法是一个绑定方法。

I am sure there is some explanation to this behavior in Pythons documentation.我确信在 Pythons 文档中对这种行为有一些解释。 Please share if you look it up :-)如果你查了,请分享:-)

调试输出

I know this question is a few years old at this point, however it was the first hit when I googled the fault.我知道这个问题在这一点上已经有几年了,但是当我用谷歌搜索故障时,这是第一次命中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM