如果值为空,则将值分配给传入类的对象
问题描述:
如果未将值分配给传递到此类的对象,我无法确定如何分配值。如果值为空,则将值分配给传入类的对象
我知道这段代码看起来有些复杂,但我把它作为一个例子来回答我的问题。
该类只是将一个数字值赋给作为对象传入的字符串中的每个字母。然后pairs.generate将打印与给定的任何字母相关的数字。如果给出的字母不在所创建的字典中,则返回0.因此,如果字典为空,则将为给出的任何字母输出0。
我想要做的就是输出,如果没有对象传递一个0,而是我收到以下错误: 类型错误:初始化()到底需要2个参数(1给出)
要查看什么是工作,传递字符串“ABCD”作为对象,并更改传递给pairs.generate()的字母。为了演示当没有对象传递时我想要发生的事情,在(“”)中传递一个空字符串。这将输出0,这是我想要发生的事情时,没有对象传入,而不是收到错误消息。
class Pairs(object):
def __init__(self, letters):
print letters
counter = 1
d = {}
for x in letters:
d[x] = counter
counter +=1
self.d = d
print self.d
pass
def generate(self, letter):
print "this is the key", letter
if letter not in self.d:
print "this key isn't in the dictionary:", letter
return 0
else:
print "this is the value", self.d[letter]
return self.d[letter]
enter = Pairs()
print enter.generate("F")
编辑 我试图从我的理解传递默认参数。我尝试了几条主意:
class Plugboard(object):
if object is None:
object = ""
但是,我仍然收到相同的错误。
答
你需要明确地由您的init方法传递所需的参数或添加默认参数初始化。下面是使用默认参数的例子包括
class Pairs(object):
def __init__(self, letters=""): # added default value for letters
print (letters)
counter = 1
d = {}
for x in letters:
d[x] = counter
counter += 1
self.d = d
print(self.d)
pass # this doesn't do anything
def generate(self, letter):
print ("this is the key", letter)
if letter not in self.d:
print ("this key isn't in the dictionary:", letter)
return 0
else:
print ("this is the value", self.d[letter])
return self.d[letter]
enter = Pairs() # this calls __init__, should pass 'letters'
print (enter.generate("F"))
类需要参数“信”,你不传递给它,当你实例化类。输入= Pairs(“abcdef”) – user2682863
@ user2682863我知道我没有通过一个参数。我希望我的程序等同于传递没有参数“ – Jomonsugi
您需要显式传递”“或将默认参数值设置为”“ – user2682863