2016-08-06 3 views
-1

사용자 입력을 통해 객체에 액세스하기 위해이 코드를 작성했습니다.두 개의 입력을 받고 클래스의 객체와 메소드에 액세스하는 방법은 무엇입니까?

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} 

, : 당신은 바르게 클래스 메소드를 사용하지 않는

+0

왜'Dragon.sum'인가? 당신은 이미'redfire' 인스턴스를 만들었는데, 왜 그것을 dict에 추가하지 않을까요? 이 경우'self'가 암시 적으로 전달됩니다. 또는'Dragon을 추가하십시오.** 정확한 ** 똑같은 일을 어리석은 방법 인 sum (redfire)'. –

+0

'getattr (dic1 [input_object], input_method)()'하시겠습니까? – jonrsharpe

+0

실제로 내가 어떻게 dictionary.look에서 그 메소드 부분을 가지고 있었는지 알지 못한다. 그 안에 몇 가지 메소드가있는 여러 클래스가 있다고 상상해 보자. object - 그 클래스의 메소드. 그 객체의 속성에 대한 설명. 이 경우와 같이 오브젝트 redfire를 얻은 후 입력을 통해 메소드 sum을 얻고 싶습니다. – Millw0

답변

0

def sum(self):는, 자기는 클래스의 객체를 참조하십시오.

당신은 다음과 같이 사용한다 :

# Create one dragon 
redfire = Dragon(2, 4) 
# Enter the dragon in the dict 
dic1 = {"redfire": redfire, "sum": redfire.sum(), "mul": redfire.mul()} 

따라서 당신은 기본적으로 Dragon 객체 인 객체 redfiresum() 기능을 사용 redfire.sum()을 사용하고 있습니다. 작업의 두 번째 부분에 대한

: 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])) 
+0

Xavier 그게 뭔지 물어 내가 내가 1000 개체가 있다면 사용자와 .image에서 개체와 메서드를 모두 얻고 싶습니다! 위선적 인 사전을 만들 수 없습니다. 그리고 코드를 바꾸는 방법에 의해 여전히 오류가 발생합니다. AttributeError : 'Dragon'객체에 'dic1'속성이 없습니다. – Millw0

+0

Millw0이 내 대답에 일부를 추가 했으므로 도움이됩니다.) –

0

의 방법을 저장 아무 소용이 없다 dictionary : 이미 Dragon 클래스에 저장되어 있습니다. 주석에서 jonrsharpe가 언급 했으므로 내장 된 getattr 함수를 사용하여 클래스 인스턴스의 속성을 검색 할 수 있습니다. summul과 같은 간단한 메소드와 headlegs 속성에 적용됩니다.

다음은 유용하다고 생각되는 코드의 재구성 된 버전입니다. 클래스에 __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), 
} 
getattr를 언급에 대한
+0

그게 마지막 줄에 그 d가 필요 없다는 것을 ... 당신은 내 값을 확인할 수 있습니다. z 값에 객체의 클래스 이름을 얻었습니다. lil이 도움을 청합니다. – Millw0

+0

@ Millw0 물론, 마지막 3 개 내 첫 번째 코드 블록의 줄은'print (dragons [name], getattr (dragons [name], method_name)())'로 요약 될 수 있지만 코드를 더 읽기 좋게 만들고 싶었다. –

0

정말 고마워요 everbody 특히 jonrsharp 및 PM 2Ring() 함수를 호출합니다. 아래 코드는 내가 찾고 있었던 것이다.

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])) 
+0

당신이 필요로하는 특별한 것을하지 않는 한'locals()'를 사용하는 것은 좋은 생각이 아니며, 여기에 필요하지 않습니다. 'locals()'를 사용하면 코드를 읽기가 더 어렵게되어 (유지하기가 더 어려워집니다). –

관련 문제