我的班级结构是这样的。
class A():
def __init__(self):
self.matched_condition_set = set()
def add_to_matched_condition(self,condition):
self.matched_condition_set.add(condition)
class B():
def __init__(self, list_of_A):
self.list_of_a = list_of_A
def do_stuff(self):
for a in self.list_of_a:
if helper.check_for_a(a):
print(a.matched_condition_set)
在一个名为helper.py的文件中,我具有以下功能。
def check_for_a(a):
print(type(a))
a.add_to_matched_condition("hello")
return True
现在,如果我调用B类对象,则会得到:
实例没有属性“ add_to_matched_condition”
。当我尝试print(type(a))
在helper方法中获取>>的类型时。我得到类型<'instance'>。物体在哪里丢失?
我不知道你为什么得到A instance has no attribute 'add_to_matched_condition'
; 您的代码对我在Python 2.6.4上正常工作
为了在类上获得更有用的类型签名(以及其他优点),您需要使它们从继承object
。
这是我对代码进行略微修改的版本,它说明了这一点;它还显示了我如何测试您的课程。
#!/usr/bin/env python
import helper
class A(object):
def __init__(self):
self.matched_condition_set = set()
def add_to_matched_condition(self,condition):
self.matched_condition_set.add(condition)
class B(object):
def __init__(self, list_of_A):
self.list_of_a = list_of_A
def do_stuff(self):
for a in self.list_of_a:
if helper.check_for_a(a):
print(a.matched_condition_set)
a1 = A(); a2 = A()
b = B([a1, a2])
print a1, a2
print b, b.list_of_a
b.do_stuff()
print a1.matched_condition_set
print a2.matched_condition_set
输出
<__main__.A object at 0xb758f80c> <__main__.A object at 0xb758f84c>
<__main__.B object at 0xb758f86c> [<__main__.A object at 0xb758f80c>, <__main__.A object at 0xb758f84c>]
<class '__main__.A'>
set(['hello'])
<class '__main__.A'>
set(['hello'])
set(['hello'])
set(['hello'])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句