简体   繁体   中英

Passing class variables into class methods

How do I pass class variables into class methods? I wrote a program to recursively swap every second character of a string.

Since I could not pass self.inputstring as arguments I decided to use a nested function.

Is there a better solution? Is it possible to use class variables as arguments?

class Swap(object):

def __init__(self, astring):

    self.acc = ""
    self.count = 1

    self.inputstring = astring
    self.checkstring = astring

def swap2(self):

    string = self.inputstring

    def swaphelper(string):

        if len(string) == 2:
            self.acc = self.acc + string[1] + string[0]
            self.count = self.count + 2
        if len(self.checkstring) == len(self.acc):
            return self.acc

        if len(self.checkstring) != len(self.acc):
            return swaphelper(self.inputstring[self.count-1:self.count+1])

    return swaphelper(string)


c = Swap("I'm a string")

d = c.swap2()

You can access class instance variables inside your instance methods like so.

class Swap(object):
    def __init__(self, astring):
        self.inputstring = astring


    def swap(self):
        s = self.inputstring

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