如何在一个文件中访问另一个文件的类实例?
我有两个文件,它们都在同一个项目里(这是一个网络爬虫框架的一部分)。文件1处理文件2生成的项目。在文件2里,我有一个函数可以打印出一些基本的统计信息(比如生成了多少个项目的计数等等)。在文件1里,我也有一些计数,我想把这些计数和文件2的统计信息一起打印出来,但我不太确定该怎么做。请看下面的示例代码。
文件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.
错误:
exceptions.AttributeError: type object 'Class1' has no attribute 'stats'
我知道这两个文件都是在运行的,因此'counter'类的'stats'实例也是在运行的,因为在运行项目时有其他方法的输出(这只是一个简化的例子)。我在这里做错了什么?这样做可能吗?
3 个回答
4
你的术语有点混乱。“两个文件都在运行,因此'counter'类的'stats'实例也在运行” - stats
是 counter
类的对象的一个属性。如果你想知道创建了多少个这个类的实例,你应该使用一个 类属性,这个属性是和你的类绑定在一起的,而不是和它的某个实例绑定。
class Counter(object):
count = 0
def __init__(self, name):
self.name = name
Counter.count += 1
self.id = Counter.count
def __repr__(self):
return '<Counter: %s (%d of %d)>' % (
self.name, self.id, Counter.count)
所以可以这样使用,
>>> foo = Counter('Foo')
>>> print foo
<Counter: Foo (1 of 1)>
>>> bar = Counter('Bar')
>>> print bar
<Counter: Bar (2 of 2)>
>>> print foo
<Counter: Foo (1 of 2)>
>>>
注意,当你第二次 print foo
时,计数已经更新了,但 id
还是保持不变。这是因为 count
是一个类属性,而 id
是对象的属性。所以(根据这段代码)创建 bar
并不会影响 foo
的 id
,但会增加 Counter.count
的值。
4
在文件1中,创建一个Class1的实例,然后用这个实例来获取数量。
class Class1(object):
def __init__(self):
self.stats = counter()
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
class_instance = Class1()
在文件2中,使用刚才创建的实例:
from project import file1
def stats():
print file1.class_instance.stats
8
这个问题之所以不行,是因为你从来没有创建过 Class1
的实例。
__init__
是在你创建 Class1
的实例时被调用的,这样 Class1.stats
就会被设置。
你这里有两个选择。
- 在文件2中以某种方式创建
Class1
的实例。 - 在
Class1
中声明一个静态方法,返回计数属性。