gpt4 book ai didi

python - python 类中的条件

转载 作者:行者123 更新时间:2023-12-01 08:16:07 25 4
gpt4 key购买 nike

我实际上正在开发一个项目,我想在类的 get 方法中插入条件。该条件必须将最后一个句子作为参数,并评估该句子是否返回某些内容。这是我想要做的 foo 代码:

class foo:
def __init__(self,mylist):
self.array=mylist
def first_item(self):
z=mylist[0]
if z==0:
return z
else:
print("First item is not 0")
a=foo([0,2])
b=foo(1)

print(a.first_item)
print(b.first_item)

主要目标是评估 z 是否具有任何值。

非常感谢。

最佳答案

您的代码存在几个问题

class foo:
def __init__(self,mylist):
self.array=mylist
if type(self.array) is not list: # make it a list if it isnt
self.array = [self.array]
def first_item(self):
z=self.array[0] # use your class variable, mylist doesnt exist here
if z==0:
return z
else:
return "First item is not 0" # it is not clear if you want to return this value, raise an error or just print and return nothing

a=foo([0,2])
b=foo(1)

print(a.first_item()) # the () are important, otherwise you arent calling the function
print(b.first_item())

将打印:
0
第一项不为 0

关于python - python 类中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54969414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com