2024-05-17 15:05:54 发布
网友
我想显示一个给定对象的属性,想知道是否有一个python函数。 例如,如果我有一个来自以下类的对象:
class Antibody(): def __init__(self,toSend): self.raw = toSend self.pdbcode = '' self.year = ''
我能得到一个类似的输出吗:
['self.raw','self.pdbcode','self.year']
谢谢
尝试dir(self)。它将包括所有属性,而不仅仅是“数据”。
dir(self)
以下方法打印类实例的['self.pdbcode', 'self.raw', 'self.year']:
['self.pdbcode', 'self.raw', 'self.year']
class Antibody(): ... def get_fields(self): ret = [] for nm in dir(self): if not nm.startswith('__') and not callable(getattr(self, nm)): ret.append('self.' + nm) return ret a = Antibody(0) print a.get_fields()
像这样
class Antibody: def __init__(self,toSend): self.raw = toSend self.pdbcode = '' self.year = '' def attributes( self ): return [ 'self.'+name for name in self.__dict__ ]
尝试
dir(self)
。它将包括所有属性,而不仅仅是“数据”。以下方法打印类实例的
['self.pdbcode', 'self.raw', 'self.year']
:像这样
相关问题 更多 >
编程相关推荐