python中的变量as语句?

2024-03-29 06:39:28 发布

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

我在读一些python代码时遇到了这个。因为我主要编写C和Java(variable as statement甚至没有用这些语言编译),所以我不确定它在python中是关于什么的。你知道吗

self.current,“变量作为语句”在这里是什么意思?这只是打印变量的一种方式,还是python中处理异常的一种特殊语法/实践?你知道吗

class PriorityQueue():

    def __init__(self):
        self.queue = []
        self.current = 0   

    def next(self):
        if self.current >=len(self.queue):
            self.current
            raise StopIteration

        out = self.queue[self.current]
        self.current += 1

        return out

Tags: 代码self语言queuedefas方式语法
2条回答

我意识到这可以用来检查属性/方法是否真的存在于传递的参数中。可能对输入健全性检查有用。你知道吗

def test(value):
    try:
        value.testAttr
    except AttributeError:
        print "No testAttr attribute found"

它实际上什么都不做,唯一能做任何事情的方法,特别是@Daniel在评论中说的,就是如果self.current指的是property method。如下所示:

class X():
    @property
    def current(self):
        mail_admins()
        return whatever

    def next(self):
        ...

这样,调用self.current,实际上会做一些事情。你知道吗

但无论如何,这绝对不是好的做法,因为一个属性只是,一个属性,如果它应该做些什么,它应该是方法。你知道吗

相关问题 更多 >