Home > Back-end >  AttributeError: 'str' object has no attribute 'parent'
AttributeError: 'str' object has no attribute 'parent'

Time:09-27

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())

In the code above Im trying to check if the parent is set as a parent in the class Child. But i keep getting AttributeError: 'str' object has no attribute 'parent' in the is_parent() function

CodePudding user response:

In this method self. kids will be a list of strings and in the iteration, you are trying this kid.parent which will not available in a string.

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

You can rewrite the code like this,

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]))

CodePudding user response:

parent1.kids is a list of strings so no kid has a .parent attribute. Your is_parent method also only checks the first kid and then already returns True or False. You probably want to work with objects rather than passing the name along (at least thats what your type hints suggest). You can rewrite your code like this:

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))
  • Related