属性错误: 'str'对象没有属性'parent'


from typing import List

class Parent:
def __init__(self,name: str, age: int,kids: List['Child']):
self.name = name
self.age = age
self.kids = kids

def is_parent(self):
for kid in self.kids:
if kid.parent == self.name:
return True
else:
return False
class Child:
def __init__(self,name:str,age:int,parent: Parent):
self.name = name
self.age = age
self.parent = parent
parent1 = Parent("Joe",41,["Mike","Luke"])
child1 = Child("Mike",10,"Joe")
child2 =  Child("Luke",9,"Joe")
print(parent1.is_parent())

在上面的代码中,我试图检查父级是否设置为Child类中的父级。但我一直得到属性错误:"str"对象在is_parent((函数中没有属性"parent">

在这个方法中,self. kids将是一个字符串列表,在迭代中,您正在尝试这个kid.parent,它在字符串中不可用。

def is_parent(self):
for kid in self.kids:
if kid.parent == self.name: # `kid` is a string
return True
else:
return False

你可以这样重写代码,

class Parent:
def __init__(self,name: str, age: int,kids: List['Child']):
self.name = name
self.age = age
self.kids = kids

def is_parent(self, kid_names):
for kid in kid_names:
if kid in self.kids:
return True
else:
return False
class Child:
def __init__(self,name:str,age:int,parent: Parent):
self.name = name
self.age = age
self.parent = parent
parent1 = Parent("Joe",41,["Mike","Luke"])
child1 = Child("Mike",10,"Joe")
child2 =  Child("Luke",9,"Joe")
print(parent1.is_parent([child1.name, child2.name]))

parent1.childs是一个字符串列表,因此没有一个child具有.eparent属性。is_parent方法也只检查第一个孩子,然后已经返回True或False。您可能想要处理对象,而不是传递名称(至少这是您的类型提示所建议的(。你可以这样重写你的代码:

class Parent:
def __init__(self, name: str, age: int, kids: list['Child'] = None):
self.name = name
self.age = age
self.kids = kids or []
def is_parent(self, kid):
return kid.parent == self

class Child:
def __init__(self, name: str, age: int, parent: Parent):
self.name = name
self.age = age
self.parent = parent

parent1 = Parent("Joe", 41)
child1 = Child("Mike", 10, parent1)
child2 = Child("Luke", 9, parent1)
parent1.kids = [child1, child2]
print(parent1.is_parent(child2))

相关内容

  • 没有找到相关文章

最新更新