简体   繁体   中英

How to get a method's variable inside a class?

I want to get the result() method's variable that is called word .

If someone knows how to do it, please help me.

def result(self,var1,word="",mainlista=mainlista):
    try:
        for i in range(int(var1)):
            x = random.choice(mainlista)
            word += x
    except IndexError:
        pass

If you don't want result() to return word you can create an instance variable for it see example below.

import random


mainlista = ['london', 'paris', 'tokyo']


class WordPower:
    def __init__(self, var1, mainlista):
        self.var1 = var1
        self.mainlista = mainlista
        self.word = ''

    def result(self):
        try:
            for _ in range(self.var1):
                x = random.choice(self.mainlista)
                self.word += x
        except IndexError as e:
            print(e)


var1 = 2
a = WordPower(var1, mainlista)
a.result()
word = a.word
print(word)

# tokyoparis

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