python - python 类中的条件

标签 python class

我实际上正在开发一个项目,我想在类的 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/

相关文章:

Python raw_input 不会提示

C++ 类 : using a private array in a public function?

typescript - 在 Typescript 中引用父类中的嵌套类

c++ - 我因为两次定义函数而收到此错误

python - 如何通过 TOR 网络路由 urllib 请求?

python - matplotlib 中不需要的空白子图

python - 我是否必须在 Python 中引发 ValueError

python - 如何在 Python 中获取类属性的定义顺序?

C++ 从派生类的友元函数访问基类的 protected 成员

python - 对 pandas 列与其他列进行评分