Python Can';不要在类内调用静态方法
这就是我想做的 在类内调用静态方法来填充类变量Python Can';不要在类内调用静态方法,python,error-handling,static-methods,Python,Error Handling,Static Methods,这就是我想做的 在类内调用静态方法来填充类变量 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 = {}
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天前在
库存
定义(即类属性和方法定义)顶层的代码在库存
名称存在之前运行,因此您不能在定义中调用它自己的方法。既然您有一个@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
请注意,我已经做了一些整理,特别是在
计算\u total\u stock
的显式参数方面,这里确实不需要任何解决方法,只需给调用方法一个额外的指导级别
在下面的示例中,您可以在其定义类的内部和外部调用PrintThis()方法
外部:
像平常一样打电话
- MyClass.PrintThis('42')
- 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