类实例没有属性';函数名';用于在类外传递对象-python

类实例没有属性';函数名';用于在类外传递对象-python,python,function,object,Python,Function,Object,我的班级结构是这样的 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.

我的班级结构是这样的

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对象, 我明白了:

实例没有属性“将\u添加到\u匹配的\u条件”

。 另外,当我尝试在helper方法中获取一个>>
print(type(a))
的类型时。我会打字。
对象在哪里丢失了?

您看到
type
的原因很可能是您正在使用Python 2.x。因为您将类定义为

class A():
而不是

class A(object):
您正在创建“旧式”类

至于您的另一个问题,我们需要查看您在其中创建
a()
s列表并将该列表传递到构造函数中的
B()
。如果你想回答你问题的那一部分,请添加该代码


另外,我不清楚为什么
check_for_a
不是
a()
的一种方法,我也不确定我是否会命名一个函数
check_for_a
,如果它确实有改变它正在检查的对象的副作用。

我不知道为什么会得到
一个实例没有属性“add_to_matched_condition”
;您的代码在Python 2.6.4上运行正常

要在类上获得更有用的类型签名(以及其他好东西),您需要使它们从
对象
继承

这是我对你的代码稍加修改的版本,说明了这一点;它还显示了我是如何测试你的课程的

#!/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'])

[, ]
集合(['hello'])
集合(['hello'])
集合(['hello'])
集合(['hello'])

你是什么意思
调用class B object
?适用于我-
a=a();b=b([a]);b、 do_stuff()
导致
集合(['hello'])
。向类a(对象)声明一个类:解决了它。但是这两种类型之间有什么区别呢???@shubham:参见文档和