从python对象中提取特定字段

时间:2016-06-30 18:39:52

标签: python

这是我正在使用的示例python对象。

class DataObj(object):

   def __init__(self, cvid, cvname, address, get_info):
      self.cvid = cvid
      self.cvname = cvname
      self.address = address
      self.prof = PROF("Honda", "Jason Jones")


class PROF(object):

    def __init__(self, organization, manager_name):
        self.organization = organization
        self.manager_name = manager_name
        self.project_list = [Proj("asd", "asd"), Proj("asdsd", "asdsd")]
class Proj(object):
     def __init__(self, projectname, projecttype):
         self.projectname = projectname
         self.projecttype = projecttype

我需要编写一个函数,它接受一个字段列表并从 DataObj 中提取所有字段作为键值对。诀窍是它还应该查找在 DataObj 类中组成的对象的属性。例如,如果字段列表是 [" cvid"," organization"," projectname"] ,它应该返回这样的内容以下格式

{'cvid' : 'value', 'organization' : 'Honda', Proj :[{'projectname' : 'asd'}, {'projectname' : 'asdsd'}]

我应该在哪里编写这个函数,所以我的代码更模块化?我正在考虑在DataObj中编写它,但我不知道DataObj中组成的对象的属性是什么。如何以更面向对象的方式实现我想要做的事情?

2 个答案:

答案 0 :(得分:2)

我所做的只是添加__iter__,基本上说嘿,如果你将对象转换为一个iterabale容器类型,你可以迭代我。

class Proj(object):
    def __init__(self, projectname, projecttype):
        self.projectname = projectname
        self.projecttype = projecttype

    def __iter__(self):
        yield ("projectname", self.projectname)


class PROF(object):
    def __init__(self, organization, manager_name):
        self.organization = organization
        self.manager_name = manager_name
        self.project_list = [Proj("asd", "asd"), Proj("asdsd", "asdsd")]

    def __iter__(self):
        for proj in self.project_list:
            yield (dict(proj))


class DataObj(object):
    def __init__(self, cvid, cvname, address):
        self.cvid = cvid
        self.cvname = cvname
        self.address = address
        self.prof = PROF("Honda", "Jason Jones")

    def __iter__(self):
        yield ('cvid', self.cvid)
        yield ('organization', self.prof.organization)
        yield ("Proj", list(self.prof))


do = DataObj("1", "heinst", "A Street, Somewhere, USA")
print dict(do)

答案 1 :(得分:1)

__getattr__operator.attrgetter之间,您可以非常轻松地完成这项工作:

class DataObj(object):

    def __init__(self, cvid, cvname, address, get_info):
        self.cvid = cvid
        self.cvname = cvname
        self.address = address
        self.prof = PROF("Honda", "Jason Jones")

    def __getattr__(self, name):
        # Called when an attribute is accessed which is not found on DataObj
        # You can limit the loop to avoid checking some attributes, or
        # remove the loop if only self.prof should be checked
        for member in (self.cvid, self.cvname, self.address, self.prof):
            try:
                return getattr(member, name)
            except AttributeError:
                pass
        raise AttributeError(name)

        # If only self.prof should be checked, the function could simplify to:
        # return getattr(self.prof, name)

然后你可以创建一个简单的效用函数,该函数针对DataObj运行,以从中获取任意一组键值对:

from operator import attrgetter

def extractdata(dataobj, *names):
    return dict(zip(names, attrgetter(*names)(dataobj)))

或者作为DataObj的成员,只需将第一个参数self命名为匹配约定:

def extractdata(self, *names):
    return dict(zip(names, attrgetter(*names)(self)))

__getattr__允许将属性查找委派给包含的对象,attrgetter允许您以简单的方式检索一组任意属性。