简体   繁体   中英

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

I have my code as follows -

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)

Now I want to use the id and count variable in another function within the same class utils. I tried doing it as follows -

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

But this doesn't seem to work and gives the error getNextId and getCount are not defined. How to go about it?

Thanks in advance!

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

But if it's within the same class you can access the member variables directly without using getters.

You don't need to bother with getters generally, but I see you are trying to increment them each time. To call a class method from within a class, you have to use self which is a reference to the class itself.

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

One thing I'll say is to stop using str() as it isn't normally required. The cast of numbers to string when building a new string is handled automatically by Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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