我知道之前已经问过这个问题,但对于我的生活,我似乎无法理解答案,所以我在这里寻求一些帮助。我不是想浪费任何时间在这里,所以请不要互联网对我大喊大叫!
我有一个名为Enemy的类,带有变量。如何在另一个类中访问这些变量? 这是我的榜样。
import tkinter
from tkinter import ttk
class Enemy(object):
def __init__ (self, name, attack, defence, gold, health, experience):
self.name = name
self.attack = attack
self.defence = defence
self.gold = gold
self.health = health
self.experience = experience
Enemy1 = Enemy("Enemy Soldier", "5", "1", "10", "10", "30")
class Application(object):
def __init__(self):
self.enemyLabel = tkinter.Label(text= self.Enemy1.name)
self.enemyLabel.pack()
myApp = Application()
myApp.root.mainloop()
这是我的代码的缩小版本。
答案 0 :(得分:1)
您必须在enemy1
范围内定义Application.__init__
:
class Enemy(object):
def init (self, name, attack, defence, gold, health, experience):
self.name = name
self.attack = attack
self.defence = defence
self.gold = gold
self.health = health
self.experience = experience
class Application(object):
def __init__(self):
self.enemy1 = Enemy("Enemy Soldier", "5", "1", "10", "10", "30")
self.enemyLabel = tkinter.Label(text=self.enemy1.name)
self.enemyLabel.pack()
答案 1 :(得分:0)
在您创建Enemy1
的范围内的任何地方,您只需使用Enemy1.name
,Enemy1.attack
等。