2017-03-20 1 views
0

특정 클래스의 모든 필드 목록을 쉽게 표시 할 수 있습니다._meta 클래스를 사용하면 다른 클래스의 필드 목록을 표시 할 수 있습니다.

[f.name for f in EmployerProfile._meta.get_fields()] 

EmployerProfile, 우리는, 예를 들어, 다른 클래스가 있다고 가정 FinancialProfile이고 두 클래스가 서로 파생되지 않습니다. 이 특정 클래스에서 다른 클래스의 필드에 액세스하고 싶습니다. 내 말은 FinancialProfile에서 EmployerProfile의 필드 목록을 만들고 싶습니다. 어떻게 그런 일을 할 수 있니? super() 방법은 이것을 수행하는 좋은 방법입니까?

미리 감사드립니다.

답변

0

클래스는 Python의 객체이므로 런타임에 생성하거나 수정할 수 있습니다. super()를 사용하는 방법은 없습니다 - 당신의 클래스가 서로 상속하지 않는 경우 http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example

: 당신이 여기에, "메타 클래스를"이라고해야 할 것이 몇 가지 예입니다.

#!/usr/bin/python 

class A(): 
    a = 5 
    b = 'b' 
    c = "test value" 

a = A() 
print "Class A members:" 
print a.a 
print a.b 
print a.c 

# Please note that class B does not explicitly declare class A members 
# it is empty by default, we copy all class A methods in __init__ constructor 
class B(): 

    def __init__(self): 

     # Iterate class A attributes 
     for member_of_A in A.__dict__.keys(): 
      # Skip private and protected members 
      if not member_of_A.startswith("_"): 
       # Assign class A member to class B 
       setattr(B, member_of_A, A.__dict__[member_of_A]) 

b = B() 
print "Class B members:" 
print b.a 
print b.b 
print b.c 

이이 모델을 장고하지, 파이썬 클래스의 예는 다음과 같습니다 여기

는 클래스 A 멤버의 전체 사본이 C 클래스 B를 생성하는 예제이다. Django 모델 클래스의 경우 솔루션이 다를 수 있습니다.

+0

저는 python 2.7을 사용하고 있습니다. 당신의 대답을 명확히 할 수있는 것들을 추가 할 수 있습니까? –

관련 문제