【问题标题】:How to call a variable defined in one function in another function within same class in python如何在python的同一类中的另一个函数中调用一个函数中定义的变量
【发布时间】:2014-05-23 05:01:13
【问题描述】:

我的代码如下 -

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 未定义。 该怎么办?

提前致谢!

【问题讨论】:

    标签: python function class call


    【解决方案1】:
    self.Id = self.getNextId();
    self.cnt = self.getCount();
    

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-05
        • 2022-01-27
        相关资源
        最近更新 更多