Python 使用_meta类显示另一个类中的字段列表
我知道我们可以很容易地显示特定类中所有字段的列表,例如,Python 使用_meta类显示另一个类中的字段列表,python,django,class,field,Python,Django,Class,Field,我知道我们可以很容易地显示特定类中所有字段的列表,例如,employeerprofile,带有 [f.name for f in EmployerProfile._meta.get_fields()] 假设我们有另一个类,例如FinancialProfile,这两个类不是从彼此派生的。我想从这个特定类访问另一个类的字段。我的意思是我想从employeerprofile内部FinancialProfile创建一个字段列表。我怎么能做这样的事?super()方法是一种很好的方法吗 提前谢谢 类是P
employeerprofile
,带有
[f.name for f in EmployerProfile._meta.get_fields()]
假设我们有另一个类,例如FinancialProfile
,这两个类不是从彼此派生的。我想从这个特定类访问另一个类的字段。我的意思是我想从employeerprofile
内部FinancialProfile
创建一个字段列表。我怎么能做这样的事?super()
方法是一种很好的方法吗
提前谢谢 类是Python中的对象,因此您可以在运行时创建或修改它们。您需要的是“元类”,以下是一些示例: 如果您的类彼此不继承,则无法使用
super()
以下是创建c类B的示例,其中包含a类成员的完整副本:
#!/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
这是Python类的示例,而不是Django模型。对于Django模型类,解决方案可能不同。我使用的是python 2.7。你能补充一些东西来澄清你的答案吗?