我编写了这段代码来通过用户输入访问对象。它适用于当地人(我知道我也可以制作字典)
class Dragon:
def __init__(self, head, legs):
self.head = head
self.legs = legs
def sum(self):
return self.head + self.legs
redfire = Dragon(2, 4)
dic1 = {"redfire": redfire}
input_object = input()
print(dic1[input_object].sum())
但是当我尝试对班级的方法做同样的事情时:
class Dragon:
def __init__(self, head, legs):
self.head = head
self.legs = legs
def sum(self):
return self.head + self.legs
def mul(self):
return self.head * self.legs
redfire = Dragon(2, 4)
dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul}
input_object = input()
input_method = input()
print(dic1[input_object].dic1[input_method])
我收到各种错误要求我修改字典:
Traceback (most recent call last):
File "C:\Users\millw0rm\test.py", line 10, in <module>
dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul}
NameError: name 'self' is not defined
如何在字典中为我的方法定义有效密钥?
答案 0 :(得分:0)
您没有正确使用类方法:
redfire = Dragon(2, 4)
dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul}
事实上,在你的类函数定义中:def sum(self):
,self引用类的对象。
然后您应该像这样使用它:
# Create one dragon
redfire = Dragon(2, 4)
# Enter the dragon in the dict
dic1 = {"redfire": redfire, "sum": redfire.sum(), "mul": redfire.mul()}
因此,您使用redfire.sum()
基本上在sum()
对象redfire
上使用Dragon
函数。
对于你工作的第二部分:print(dic1[input_object].dic1[input_method])
,你需要存储对函数的引用:
sum_method = Dragon.sum
sum_redfire = sum_method(redfire)
最后我们得到:
redfire = Dragon(2, 4)
sum_method = Dragon.sum
dict1 = {"redfire": redfire, "sum": sum_method}
input_object = input()
input_method = input()
print(dict1[input_method](dict1[input_object]))
答案 1 :(得分:0)
将方法存储在字典中是没有意义的:它们已经存储在Dragon类本身中。正如jonrsharpe在评论中提到的那样,您可以使用内置的getattr
函数来检索类实例的属性;这适用于sum
和mul
以及简单head
和legs
属性等方法。
以下是我认为您会发现有用的代码的重新组织版本。我在类中添加了__repr__
方法,以便在打印Dragon实例时获得有用的信息。
class Dragon:
def __init__(self, head, legs):
self.head = head
self.legs = legs
def sum(self):
return self.head + self.legs
def mul(self):
return self.head * self.legs
def __repr__(self):
return 'Dragon({}, {})'.format(self.head, self.legs)
dragons = {}
dragons["redfire"] = Dragon(2, 4)
dragons["greenfire"] = Dragon(1, 2)
print(dragons)
name = input("name: ")
method_name = input("method: ")
d = dragons[name]
method = getattr(d, method_name)
print(d, method())
<强>测试强>
{'redfire': Dragon(2, 4), 'greenfire': Dragon(1, 2)}
name: redfire
method: sum
Dragon(2, 4) 6
当然,您可以创建dragons
字典,如下所示:
dragons = {
"redfire": Dragon(2, 4),
"greenfire": Dragon(1, 2),
}
答案 2 :(得分:0)
非常感谢jonrsharp和PM 2Ring提到getattr()函数。下面的代码是我正在寻找的
class Dragon:
def __init__(self,head,tail):
self.head=head
self.tail=tail
def sum(self):
return (self.head + self.tail)
class Snake:
def __init__(self,head,tail):
self.head=head
self.tail=tail
def sum(self):
return (self.head * self.tail)
python=Snake(1,1)
anakonda=Snake(3,5)
redfire=Dragon(2,4)
hellfly=Dragon(2,10)
x=input()
y=input()
z=objectdic[x].__class__.__name__
print(getattr(locals()[z],y)(locals()[x]))