AttributeError:NoneType对象没有属性

时间:2015-05-31 06:56:50

标签: python nonetype

作为python新手,我在执行作者收到的代码时收到以下错误消息:

line 412, in add_family
    mother_birth_ref = mother.get_birth_ref()
AttributeError: 'NoneType' object has no attribute 'get_birth_ref'

代码的相关部分必须在此处:

def write_child_stats(self):
    file = open("%s/intern/child-stats.txt" % self.dir_name, 'w')

def add_family(family, marriage_event, divorce_event):
    father_handle = family.get_father_handle()
    mother_handle = family.get_mother_handle()

    father = self.database.get_person_from_handle(father_handle)
    father_birth_ref = father.get_birth_ref()
    father_birth = None
    if father_birth_ref:
        father_birth = self.database.get_event_from_handle(father_birth_ref.ref)

    mother = self.database.get_person_from_handle(mother_handle)
    mother_birth_ref = mother.get_birth_ref()
    mother_birth = None
    if mother_birth_ref:
        mother_birth = self.database.get_event_from_handle(mother_birth_ref.ref)

    children = []
    child_refs = family.get_child_ref_list()
    for child_handle in child_refs:
        child = self.database.get_person_from_handle(child_handle.ref)
        if child:
            child_birth_ref = child.get_birth_ref()
            if child_birth_ref:
                child_birth = self.database.get_event_from_handle(child_birth_ref.ref)
                children.append("%04d-%02d-%02d" % child_birth.get_date_object().get_ymd())

如何解决问题?

1 个答案:

答案 0 :(得分:1)

 mother = self.database.get_person_from_handle(mother_handle)

此行正在返回None。检查get_person_from_handle功能。

或者,您可以添加支票:

mother = self.database.get_person_from_handle(mother_handle)
mother_birth_ref = None
mother_birth = None
if mother:
    mother_birth_ref = mother.get_birth_ref()
if mother_birth_ref:
    mother_birth = self.database.get_event_from_handle(mother_birth_ref.ref)