【问题标题】:Printing a def from another def within the same class从同一类中的另一个 def 打印 def
【发布时间】:2018-04-01 17:03:13
【问题描述】:

我正在尝试打印我在 def 中编码的内容。 结果,我没有得到print,而是得到: <function Partie.afficher_etat_donnes at 0x000000FF03B4C950>

代码是这样的:

class Partie:
    def __init__(self, plateau, donnes):
        self.plateau = plateau
        self.donnes = donnes
        self.tour = None
        self.passe = 0
        self.gagnant = None
    @staticmethod
    def show_instructions():
        instructions = """

    Game Instructions :
            """
        print(instructions)
        print(Partie.afficher_etat_donnes)

    def afficher_etat_donnes(self):
        for joueur in range(self.nombre_joueurs):
            print(f"The player {joueur} has {len(donnes[joueur])} dominos in hand.")

对于重要的变量...在这种情况下: joueur = 2 donnes = [[3,1],[3,2]],[[6,6],[6,3] Donnes 只是一个例子。 结果我应该有: The player 0 has 2 dominos in hand.

【问题讨论】:

  • 不要打印函数名称。调用函数来执行它 - 删除 ``print( ... )` 并在函数名称后添加 () 以调用它。为此,您还需要一个类 Instance - afficher_etat_donnes(self) 不是静态函数。
  • 对不起,我在缩进中弄错了。
  • 如果我更改Partie.affichier_etat_donnes() 的代码,我会得到..TypeError: afficher_etat_donnes() missing 1 required positional argument: 'self'
  • 那是因为它是一种非静态方法,它在 Partie 的实例上运行 - 而不是在类本身上运行。 self 是自动提供的,如果您有 p = Partie(....., ... ) 并致电 p.afficher_eatat_donnes()

标签: python python-3.x


【解决方案1】:

像这样试试 - 我不会说法语,也不会玩多米诺骨牌,但这段代码有点用:

class Partie:
    def __init__(self, plateau, donnes):
        self.plateau = plateau
        self.donnes = donnes
        self.tour = None
        self.passe = 0
        self.gagnant = None
        self.nombre_joueurs = 3  # added


    @staticmethod
    def show_instructions(somePartie):
        instructions = """

    Game Instructions :
            """
        print(instructions)
        somePartie.afficher_etat_donnes()  # changed, needs instance of partie to call 
                                           # non static method on the instance....


    def afficher_etat_donnes(self):
        for joueur in range(self.nombre_joueurs):
            # fixed missing self.
            print(f"The player {joueur} has {len(self.donnes[joueur])} dominos in hand.") 

# make a Partie
p = Partie("",[[1,1,1,1],[2,2,2,2,2,2],[2,2,2]])
# call static method, give it instance of partie to enable calling other method
Partie.show_instructions(p)

输出:

    Game Instructions :

The player 0 has 4 dominos in hand.
The player 1 has 6 dominos in hand.
The player 2 has 3 dominos in hand.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 2022-12-30
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多