我有两个文件,都在同一个项目中(网络抓取框架的一部分)。 File1 处理 File2 生成的项目。在 File2 中,我有一个函数可以打印出有关进程的一些基本统计信息(已生成的项目数等)。我在 File1 中有计数,我想使用 File1 中的统计信息打印这些计数,但不确定如何执行此操作。看一下示例代码。
FILE 1:
class Class1(object):
def __init__(self):
self.stats = counter("name") #This is the instance that I'd like to use in File2
self.stats.count = 10
class counter:
def __init__(self, name):
self.name = name
self.count = 0
def __string__(self):
message = self.name + self.count
return message
文件2:(这就是我想做的)
from project import file1 # this import returns no error
def stats():
print file1.Class1.stats # This is where I'm trying to get the instance created in Class1 of File2.
#print file1.Class1.stats.count # Furthermore, it would be nice if this worked too.
ERROR:
exceptions.AttributeError: type object 'Class1' has no attribute 'stats'
我知道这两个文件都在运行,因此“counter”类的“stats”实例也在运行,因为运行项目时会打印出其他方法(这只是一个精简的示例。我在这里做错了什么?这可以吗?
这不起作用,因为你从未实例化Class1
.
__init__
当Class1
被实例化所以Class1.stats
is set.
这里你有两个选择。
- 实例化
Class1
以某种方式在文件2中。
- 声明一个静态方法
Class1
返回计数属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)