2012-02-05 13 views
3

설명하기가 다소 어려워요. 나는 더 이상의 클래스로 구성 모듈이 : someModule.py를리플렉션을 사용하여 모듈과 클래스를 들여다보기

#imports over here 
class Default(Base): 
def __init__(self): 
    a = Rectangle() #all these guys derive from Shape 
    b = Circle() 
    c = Sphere() 

class Foo: 
#members over here 

#other classes/functions/whatever we can define here, except the boiler plate code to check __main__ 

내가 뭘 원하는 것은 런타임에 특정 기본 클래스 (. 예를 들어 자료)에서 파생 클래스의 객체를 생성하고 다른 특정 기본 클래스 (예 : Shape)에서 파생 된 데이터 멤버를 조작합니다. 의미 나는 모듈 이름을 소요하고 위의 작업을 수행하는 스크립트를 작성하고 싶습니다. 어떤 아이디어를 검사 나 다른 것을 사용해서 어떻게 할 수 있습니까? 나는 조사를 보았지만 일을 끝내야 할 방법을 찾지 못했습니다. 나는 뭔가를 놓칠지도 모른다.

답변

1

인스턴스를 생성하기 전에 내부 __init__ 무엇을 알 수있는 방법은 없습니다.

에만 이후를 확인할 수 있습니다

, 그리고 그것을 할 수있는 한 가지 방법은 vars() 함께 :

:

defy = Default() 
for name,value in vars(defy).items(): 
    if isinstance(value, Shape): 
     # manipulate 

Base의 서브 클래스 인 someModule.py의 모든 클래스에서 위의 작업을 수행하려면

,536 : 당신이 Shape 서브 클래스를 통해 인스턴스 될 것되는 조작하려는 경우
import someModule 

instances = [] 
for cls_name,cls in vars(someModule): 
    if issubclass(cls, Base): 
     obj = cls() 
     for name,value in vars(cls).items(): 
      if isinstance(value, Shape): 
       # manipulate 
     instances.append(obj) 

대신, 당신은 그 (것)들에게 클래스 속성, 예를하게해야합니다

class Default(Base): 
    default_shapes = [Rectangle, Circle, Sphere] 
    def __init__(self): 
     self.shapes = [shape() for shape in self.__class__.default_shapes] 
0

기본 클래스 (예 : 기본, 도형)가 새로운 스타일 클래스 (이들은 object에서 상속 받음)인지 확인하십시오. 이렇게하면 내장 된 __subclasses__() 함수를 사용하여 파생 된 모든 클래스의 목록을 가져올 수 있습니다. 그럼 당신은 단순히 개체를 만들고 관심있는 클래스와 비교, 필드를 통해 갈 수 있습니다.

baseDerived = Base.__subclasses__() 
shapeDerived = Shape.__subclasses__() 

# Iterate through derived classes 
for derivedClass in baseDerived: 
    derivedObject = derivedClass() 

    # Iterate through data attributes 
    for attr, dataMember in derivedObject.__dict__.iteritems(): 
     if dataMember.__class__ in shapeDerived: 
      # Do stuff with the data member here 
관련 문제