사용자 입력을 통해 객체에 액세스하기 위해이 코드를 작성했습니다.두 개의 입력을 받고 클래스의 객체와 메소드에 액세스하는 방법은 무엇입니까?
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])
나는 모든 종류의를 받고 있어요 : 그것은
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())
을 (내가 사전도 만들 수있어)하지만 클래스의 방법과 동일한 작업을 수행하기 위해 노력하고있어 때 지역 주민과 함께 작동 내 사전을 수정하려면 나 한테 물어 오류 :
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
내 사전에 내 방법에 대한 유효한 키를 정의하기 위해 무엇을 할 수 있는가? 클래스 함수 정의에 사실
redfire = Dragon(2, 4)
dic1 = {"redfire": redfire, "sum": Dragon.sum(self), "mul": Dragon.mul}
, : 당신은 바르게 클래스 메소드를 사용하지 않는
왜'Dragon.sum'인가? 당신은 이미'redfire' 인스턴스를 만들었는데, 왜 그것을 dict에 추가하지 않을까요? 이 경우'self'가 암시 적으로 전달됩니다. 또는'Dragon을 추가하십시오.** 정확한 ** 똑같은 일을 어리석은 방법 인 sum (redfire)'. –
'getattr (dic1 [input_object], input_method)()'하시겠습니까? – jonrsharpe
실제로 내가 어떻게 dictionary.look에서 그 메소드 부분을 가지고 있었는지 알지 못한다. 그 안에 몇 가지 메소드가있는 여러 클래스가 있다고 상상해 보자. object - 그 클래스의 메소드. 그 객체의 속성에 대한 설명. 이 경우와 같이 오브젝트 redfire를 얻은 후 입력을 통해 메소드 sum을 얻고 싶습니다. – Millw0