我想让构造函数重载,在这里我可以同时为两个参数和实际数量传递无。
class ABC(object):
def __init__(self, query = None, cands = None):
if query != None and cands != None:
self.query = query
self.cands = cands
self.getIDF()
def getIDF(self):
self.i_dict = {}
for term in query:
count = 0
for cand in cands:
if term in cand:
count += 1
self.i_dict[term] = count
然后我创建实例:abc = ABC(query, cands)
由于查询和Cands不是None,因此应该触发self.getIDF()
,但仍然出现错误:
NameError: name 'query' is not defined
似乎查询未传递到函数中,为什么?
答案 0 :(得分:1)
您可以在课堂上进行一些更改和修正
您想使用self在query
中调用类属性cands
和getIDF
,因此它将变为self.query
和self.cands
。 / p>
您只能执行if query and cands:
而不是if query != None and cands != None:
。
考虑在构造函数本身中定义self.i_dict = {}
具有这些建议的更新的类可能看起来像
class ABC(object):
def __init__(self, query = None, cands = None):
#i_dict defined in constructor
self.i_dict = {}
#Changed the if condition
if query and cands:
self.query = query
self.cands = cands
self.getIDF()
def getIDF(self):
#Use self to call class attribute
for term in self.query:
count = 0
# Use self to call class attribute
for cand in self.cands:
if term in cand:
count += 1
self.i_dict[term] = count