繁体   English   中英

如何在python的同一类中的另一个函数中调用一个函数中定义的变量

[英]How to call a variable defined in one function in another function within same class in python

我的代码如下 -

class utils :
    def __init__(self) :
        self.Name = 'Helen'
        self.count = 0
        self.idcount = 0
        self.date = datetime.datetime.now().strftime("%Y%m%d")

    def getNextId(self) :
        self.idcount += 1
        id = (self.Name+str(self.idcount)+self.date)
        return(id)

    def getCount(self) :
        self.count += 1
        count = str(self.count)
        return(count)

现在我想在同一个类 utils 中的另一个函数中使用 id 和 count 变量。 我尝试按如下方式进行 -

    def formatField(self) :
        self.Id = getNextId().id
        self.cnt = getCount().count
        return(self.cnt+','+self.Id+'            ')

但这似乎不起作用并给出错误 getNextId 和 getCount 未定义。 怎么办?

提前致谢!

self.Id = self.getNextId();
self.cnt = self.getCount();

但是如果它在同一个类中,您可以直接访问成员变量而无需使用 getter。

您通常不需要理会 getter,但我看到您每次都试图增加它们。 要从类中调用类方法,您必须使用 self ,它是对类本身的引用。

def formatField(self) :
    self.Id = self.getNextId()
    self.cnt = self.getCount()
    return(self.cnt+','+self.Id+'    ')

我要说的一件事是停止使用 str() 因为它通常不是必需的。 构建新字符串时将数字转换为字符串由 Python 自动处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM