alu*_*ach 6 python class instance
我有两个文件,都在同一个项目中(Web抓取框架的一部分).File1处理由File2生成的项目.在File2中,我有一个函数可以打印出有关进程的一些基本统计信息(生成了多少项的计数等).我在File1中有计数,我想用File1的统计数据打印但不确定如何做到这一点.看一下示例代码.
文件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
Run Code Online (Sandbox Code Playgroud)
文件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.
Run Code Online (Sandbox Code Playgroud)
错误:
exceptions.AttributeError: type object 'Class1' has no attribute 'stats'
Run Code Online (Sandbox Code Playgroud)
我知道这两个文件都在运行,因此'counter'类的'stats'实例也是如此,因为在运行项目时打印出其他方法(这只是一个简单的例子.我在这里做错了什么?这可能吗?
这不起作用,因为你永远不会实例化Class1
.
__init__
在Class1
实例化时调用,因此Class1.stats
设置.
你有两个选择.
Class1
以某种方式在文件2中实例化.Class1
,返回count属性.