试图在另一个函数中使用一个函数的返回值,但得到的却是未定义的变量

2024-03-28 14:13:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

class Pet(object):

    def __init__(self,name=""):
        self.name = name 
        self.kind = "Unknown"
        self.toys = []  
    def add_toys(self,toys):
        new_list = []
        for toy in self.toys:
            if toy not in new_list:
                new_list.append(toy)   
        return new_list
    def __str__(self):
        toys_list = add_toys(self,toys)  
        if self.toys == []:
            return "{} is a {} that has no toys".format(self.name,self.kind)
        else:
            return "{} is a {} that has the following toys: {}".format(self.name,self.kind,toys_list)     

在函数add_toys()中,我有返回值new_list。 我想在函数__ str__中使用该返回值,并将其定义为toys_list。 然而,当我写toys_list = add_toys(self, toys)时,它说:

add_toys is an undefined variable


Tags: nameinselfaddnewreturnifthat
3条回答

问题是未定义的函数。缺少引用self(每个类成员、字段或方法都需要): toys_list = self.add_toys()

重新考虑设计

为什么收集玩具要管理两次? (a) 因为字段toys可以有重复项, (b) 作为从add_toys返回,它将隐藏重复项并确保元素的唯一性

您必须保持两者同步。它们的功能不同,应该应用于不同的用例

假设:独特的玩具

我还将使用集作为字段toys的直接类型。因为通过这种方式,您可以重用现有的数据结构,它保证了您在^{中显式实现的唯一性。此外,添加/更新功能便于修改集合

改进:字符串构建

此外,还可以重构字符串函数:

def __str__(self):
    subject = "{} is a {}".format(self.name, self.kind)
    hasToys = "has no toys" if not self.toys else "has the following toys: {}".format(self.toys)
    return "{subject} that {hasToys}".format (subject, hasToys)

它使用一个三元运算符,而不是if语句;通过直接引用(通过self!)新的set字段:self.toys 加上一个三步结构,允许单次返回,作为结尾清晰可见的预期

你的add_toys方法不好,你没有使用toys参数,它不应该返回任何东西,应该是这样的

class Pet:
    # __init__ is OK

    def add_toys(self, *toys):
        for toy in toys:
            if toy not in self.toys:
                self.toys.append(toy)

    def __str__(self):
        if not self.toys:
            return "{} is a {} that has no toys".format(self.name, self.kind)
        else:
            return "{} is a {} that has the following toys: {}".format(self.name, self.kind, self.toys)

p = Pet("Foo")
p.add_toys("ball")
p.add_toys("plate", "frisbee")
print(p) # Foo is a Unknown that has the following toys: ['ball', 'plate', 'frisbee']

您可以直接使用set

class Pet:

    def __init__(self, name, kind="Unknown"):
        self.name = name
        self.kind = kind
        self.toys = set()

    def add_toys(self, *toys):
        self.toys.update(toys)

在add_toys中,第一件事是从类级变量中访问toys变量,因此删除该参数,第二件事是add_toys(self,toys)语法不正确,需要像self.add_toys()一样使用它

class Pet(object):
    def __init__(self,name=""):
        self.name = name
        self.kind = "Unknown"
        self.toys = []
    
    def add_toys(self):
        new_list = []
        for toy in self.toys:
            if toy not in new_list:
                new_list.append(toy)
        return new_list
    
    def __str__(self):
        toys_list = self.add_toys()
        if self.toys == []:
            return "{} is a {} that has no toys".format(self.name, self.kind)
        else:
            return "{} is a {} that has the following toys: {}".format(self.name, self.kind, toys_list)

备选方案:

class Pet(object):
    def __init__(self,name=""):
        self.name = name
        self.kind = "Unknown"
        self.toys = []
    
    def add_toys(self, toys):
        new_list = []
        for toy in toys:
            if toy not in new_list:
                new_list.append(toy)
        return new_list
    
    def __str__(self):
        toys_list = self.add_toys(self.toys)
        if self.toys == []:
            return "{} is a {} that has no toys".format(self.name, self.kind)
        else:
            return "{} is a {} that has the following toys: {}".format(self.name, self.kind, toys_list)

相关问题 更多 >