python类中的条件[关闭]

问题描述 投票:1回答:2

我实际上正在处理一个项目,我想在一个类的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是否具有任何价值。

非常感谢。

python class
2个回答
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

需要注意的一些重要事项:

  1. 应始终将列表传递给输入。否则它会表现得很奇怪(尝试传递一个字典并检查..)
  2. 应该经常检查空输入。
  3. 如果您未传递预期的第一个项目,则默认值为零0。这意味着如果你的列表是字符串:['a', 'b', 'c'],你会比较'a' == 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

© www.soinside.com 2019 - 2024. All rights reserved.