2010-12-08 5 views
4

나는 여러 가지 방법을 구현하는 클래스가 있다고 가정합니다. 우리는 사용자가 기존의 메소드 중에서 실행할 메소드를 선택하기를 원하거나 on_the_fly 메소드를 추가 할 수 있습니다. 파이썬, 동적으로 클래스를 구현하십시오

RemoveNoise.raw = Raw() 
RemoveNoise.bais = Bias() 
etc 

를 원 예에서

class RemoveNoise(): 
     pass 

는 방법이 추가됩니다

그는 심지어 새

def new(): 
    pass 

도 추가 new() 방법을 쓸 수

RemoveNoise.new=new 
run(RemoveNoise) 

run()은 이러한 클래스를 평가하는 함수입니다.

class_with_the_methods_used를 저장하고이 클래스를 생성 된 개체에 연결하려고합니다.

이 문제를 해결하는 방법에 대한 힌트가 있습니까?

+0

여러 명의 사용자가 동일한 클래스를 수정하게됩니까? 인스턴스를 수정하고 싶습니까? – kevpie

+0

사용자는 원하는 방법을 선택하거나 자신의 방법을 정의 할 수 있습니다. – shaz

+0

"저장"및 "링크"의 의미를 설명하십시오. 당신은 어떻게 든 영구 객체를 가지고 있다고 말하려고하고 있으며, 각 객체는 자신 만의 메소드 집합을 가질 수 있습니까? 그것은 완벽하게 가능합니다 (심지어 어렵지도 않음). 그런데 잘못된 질문을하고 있습니다. :) –

답변

6

런타임에 함수를 클래스에 추가 할 수 있습니다.

class Foo(object): 
    pass 

def bar(self): 
    print 42 

Foo.bar = bar 
Foo().bar() 
+0

빌어 먹을, 내가 무슨 일이 있었는지, 실제 문제는 언급하지 않았다, 사용자가 내가 class_with_the_methods_used를 저장하고 생성 된 객체에이 클래스를 링크하는 데 필요한 메소드를 선택한 후에. – shaz

+0

@shaz : 질문을 업데이트 할 필요가 있다고 들리는데 ... – martineau

2

해결할 필요가 없습니다. 다음은 약간의 변경이 필요한 코드입니다.

class RemoveNoise(): 
     pass 

RemoveNoise.raw = Raw 
RemoveNoise.bias = Bias 

def new(self): 
    pass 

RemoveNoise.new=new 

instance = RemoveNoise() 

간단합니다. 파이썬은 훌륭합니다.

왜 지구상에 너는 나를 넘어야 할 필요가 있을까?

+1

'new()'메소드가 기본적으로 호출 할 수 없다는 점을 제외하고는. –

+0

아 맞아. 결정된. –

+0

실제 문제는 class_with_the_methods_used를 저장하고이 클래스를 생성 된 객체에 연결하는 방법이었습니다. – shaz

0

음, 내가 묻는 것 같아요 - "나는 class_with_the_methods_used를 저장하고 싶습니다."라고 썼을 때 "save"으로 무엇을 의미하는지 잘 모르겠지만 여기에 몇 가지 코드가 있습니다. 또한 사용자 입력에 exec 문을 사용하면 매우 일 수 있습니다. 신뢰할 수없는 출처에서 오는 경우 위험합니다.

import copy 

# an empty "template" class 
class Generic(): 
    pass 

# predefined functions that create common methods 
def Raw(): 
    def raw(self): 
     print 'in Raw method of instance', id(self) 
    return raw 

def Bias(): 
    def bias(self): 
     print 'in Bias method of instance', id(self) 
    return bias 

def user_new_function(definition): 
    tempdict = {} 
    exec definition in tempdict 
    return tempdict['new'] 

# create a new class 
RemoveNoise = copy.deepcopy(Generic) 
RemoveNoise.__name__ = 'RemoveNoise' # change the class name of the copy 

# add a couple of predefined methods 
RemoveNoise.raw = Raw() 
RemoveNoise.bias = Bias() 

# add user defined 'new' method 
user_new_def = """\ 
def new(self): 
    print 'in user defined method "new" of instance', id(self) 
""" 
RemoveNoise.new = user_new_function(user_new_def) 

# create and use an instance of dynamically defined class 
instance = RemoveNoise() 
print 'RemoveNoise instance "{}" created'.format(id(instance)) 
# RemoveNoise instance "11974736" created 
instance.raw() 
# in Raw method of instance 11974736 
instance.bias() 
# in Bias method of instance 11974736 
instance.new() 
# in user defined method "new" of instance 11974736 
관련 문제