我实际上是在一个项目上,我想在类的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是否具有任何值。
非常感谢您。
答案 0 :(得分:1)
您的代码有几个问题
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
答案 1 :(得分:0)
尝试一下:
class Foo:
def __init__(self, mylist):
self.array = mylist
def first_item(self, should_be=0):
if len(self.array) > 0: # inserted list can be empty
first = self.array[0]
if first == should_be:
print(first)
else:
print(f"First item is not {should_be}")
else:
print("empty list")
a = Foo([0,2])
b = Foo([1])
c = Foo([])
d = Foo([2,3])
a.first_item() # 0
b.first_item() # "First item is not 0"
c.first_item(4) # empty list
d.first_item(2) # 2
一些重要的注意事项:
0
。这意味着如果您的列表是字符串:['a', 'b', 'c']
,您将比较'a' == 0
,这也很奇怪。