Python 如何在methode内部使用构造函数中的变量?

Python 如何在methode内部使用构造函数中的变量?,python,python-3.x,Python,Python 3.x,大家好,希望你们做得很好,我是python新手:) 因此,我有两个问题:第一个问题是如何使用init到我的函数game()中的变量名,它使用两个参数(这些参数对我来说非常困难!),正如您在下面的代码中所看到的: # FUNCTION.py class penGame(): def __init__(self): print("Welcome to Pendu Game") self.name = input("Enter your name: ") # IMPORT THIS V

大家好,希望你们做得很好,我是python新手:) 因此,我有两个问题:第一个问题是如何使用init到我的函数game()中的变量名,它使用两个参数(这些参数对我来说非常困难!),正如您在下面的代码中所看到的:

# FUNCTION.py
class penGame():
def __init__(self):
    print("Welcome to Pendu Game")
    self.name = input("Enter your name: ") # IMPORT THIS VARIABLE FROM HERE

def game(self, letter, rword):
    letter = letter.lower()
    if letter in rword:
        for Id, Value in enumerate(rword):
            if Value == letter:
                donnee.default_liste[Id] = letter
    else:
        name2 = self.name # it deosn't work i got 1 missing arg when i run the code from MAIN.py
        print(f"try again {name} it's wrong ")
    print("-".join(donnee.default_liste))
第二个问题是我需要在另一个模块中使用来自init的相同变量(name),该模块是我的主模块,我无法使用它,因为我试图从类penGame()创建对象,如:

myObject = penGame()
name2 = myObject.name
然后使用if条件中的name2,如下所示,但它不能正常工作,因为它再次运行init,这不是我实际想要的! 你知道我该怎么做吗

#MAIN.py
import donnee
from fonctions import penGame

random_word = random.choice(donnee.liste_words)  # creation of random word from liste_words
penGame()  #call the constructor
while donnee.counter < donnee.score:
    letter = input("Enter the letter: ")
    if penGame.check(letter):
        print("You cant use more one letter or numbers, try again !")  
    else:
        penGame.game(letter, random_word) # as u can see that's the reason cause i supposed to send 3 args instead of two ! but i only need those two !!?
    if penGame.check_liste():
        myObject = penGame() # that's cause runing the init everytime !!
        name2 = myObject.name
        print(f"congratulation {name2} you've guessed the word, your score is: {donnee.choice-donnee.counter} point.")
        break
    if penGame.loser():
        print(f"the word was {random_word.upper()} you have done your chances good luck next time.")
    donnee.counter += 1
#MAIN.py
进口唐尼
从Fontions导入penGame
random_word=random.choice(donnee.liste_words)#从liste_words创建随机单词
penGame()#调用构造函数
而donnee.counter
提前谢谢你,希望你能帮我,如果我的英语不太好,请原谅:):)

1.错误

您在类penGame上调用方法,而不是在penGame实例上调用方法。 这会导致缺少参数错误,因为该方法需要类的实例(self
参数),但没有得到实例。 而是使用变量(来自第二个解决方案):

在其他调用中将
penGame
替换为
mygame


  • 错误
  • 将调用的结果保存在变量中,您将不需要重新创建它

    mygame = penGame()  # call the constructor
    
    然后可以删除该行:

    myObject = penGame() # that causes the init to run again because it creates a new instance!
    
    myObject = penGame() # that causes the init to run again because it creates a new instance!