def __init__(self, master): super().__init__(master) self.grid() self.buttonStart = Button(self, text="Start Game", command=self.startGame) self.buttonStart.grid(row=0, column=1) self.entName1 = Entry(self) self.entName1.grid(row=1, column=0) self.labelPrompt = Label(self, text="Enter player names") self.labelPrompt.grid(row=1, column=1) self.entName2 = Entry(self) self.entName2.grid(row=1, column=2) self.textStats1 = Text(self, width=20, height=20) self.textStats1.grid(row=2, column=0) self.labelStats = Label(self, text="Hero Stats") self.labelStats.grid(row=2, column=1) self.textStats2 = Text(self, width=20, height=20) self.textStats2.grid(row=2, column=2) self.buttonFight = Button(self, text="Fight!", command=self.fight) self.buttonFight.grid(row=3, column=1) # create a superhero object and store in frame. Cannot store in main with GUI self.p1 = Superhero() self.p2 = Superhero()
def __init__(self, *args, **kwargs): # So instead we explicitly call __init__ for all ancestors. # The use of *args and **kwargs allows for a clean way to pass arguments, # with each parent "peeling a layer of the onion". Superhero.__init__(self, 'anonymous', movie=True, superpowers=['Wealthy'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # override the value for the name attribute self.name = 'Sad Affleck'
def __init__(self, *args, **kwargs): # Typically to inherit attributes you have to call super: # super(Batman, self).__init__(*args, **kwargs) # However we are dealing with multiple inheritance here, and super() # only works with the next base class in the MRO list. # So instead we explicitly call __init__ for all ancestors. # The use of *args and **kwargs allows for a clean way to pass arguments, # with each parent "peeling a layer of the onion". Superhero.__init__(self, 'anonymous', movie=True, superpowers=['Wealthy'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # override the value for the name attribute self.name = 'Sad Affleck'
def __init__(self, *args, **kwargs): # Обычно для наследования атрибутов необходимо вызывать super: # super(Batman, self).__init__(*args, **kwargs) # Однако здесь мы имеем дело с множественным наследованием, а super() # работает только со следующим базовым классом в списке MRO. # Поэтому вместо этого мы вызываем __init__ для всех родителей. # Использование *args и **kwargs обеспечивает чистый способ передачи # аргументов, когда каждый родитель "очищает слой луковицы". Superhero.__init__(self, 'анонимный', movie=True, superpowers=['Богатый'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # переопределить значение атрибута name self.name = 'Грустный Бен Аффлек'
def __init__(self, *args, **kwargs): # Typically to inherit attributes you have to call super: #super(Batman, self).__init__(*args, **kwargs) # However we are dealing with multiple inheritance here, and super() # only works with the next base class in the MRO list. # So instead we explicitly call __init__ for all ancestors. # The use of *args and **kwargs allows for a clean way to pass arguments, # with each parent "peeling a layer of the onion". Superhero.__init__(self, 'anonymous', movie=True, superpowers=['Wealthy'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # override the value for the name attribute self.name = 'Sad Affleck'
def __init__(self, window): super().__init__(window) self.config(background="#ffcc00") self.grid() self.startButton = Button(self, text="Start Game", bg="#990000", command=self.startGame) self.startButton.grid(row=0, column=1) self.p1StringVar = StringVar() self.p1StringVar.set("") self.p1Entry = Entry(self, textvariable=self.p1StringVar, state=DISABLED) self.p1Entry.grid(row=1, column=0) self.playerLabel = Label(self, text="Enter Player Names", state=DISABLED) self.playerLabel.grid(row=1, column=1) self.p2StringVar = StringVar() self.p2StringVar.set("") self.p2Entry = Entry(self, textvariable=self.p2StringVar, state=DISABLED) self.p2Entry.grid(row=1, column=2) self.hero1Text = Text(self, width=20, height=20, state=DISABLED) self.hero1Text.grid(row=2, column=0) self.heroLabel = Label(self, text="Hero Stats", state=DISABLED) self.heroLabel.grid(row=2, column=1) self.hero2Text = Text(self, width=20, height=20, state=DISABLED) self.hero2Text.grid(row=2, column=2) self.fightButton = Button(self, text="Fight!", state=DISABLED, command=self.fight) self.fightButton.grid(row=3, column=1) # Superhero objects self.p1 = Superhero() self.p2 = Superhero()
# that are overridden by the child, in this case, the __init__ method. # This calls the parent class constructor: super().__init__(name) # override the sing method def sing(self): return 'Dun, dun, DUN!' # add an additional instance method def boast(self): for power in self.superpowers: print("I wield the power of {pow}!".format(pow=power)) if __name__ == '__main__': sup = Superhero(name="Tick") # Instance type checks if isinstance(sup, Human): print('I am human') if type(sup) is Superhero: print('I am a superhero') # Get the Method Resolution search Order used by both getattr() and super() # This attribute is dynamic and can be updated print(Superhero.__mro__) # => (<class '__main__.Superhero'>, # => <class 'human.Human'>, <class 'object'>) # Calls parent method but uses its own class attribute print(sup.get_species()) # => Superhuman
class Application(Frame): # constructor def __init__(self, window): super().__init__(window) self.config(background="#ffcc00") self.grid() self.startButton = Button(self, text="Start Game", bg="#990000", command=self.startGame) self.startButton.grid(row=0, column=1) self.p1StringVar = StringVar() self.p1StringVar.set("") self.p1Entry = Entry(self, textvariable=self.p1StringVar, state=DISABLED) self.p1Entry.grid(row=1, column=0) self.playerLabel = Label(self, text="Enter Player Names", state=DISABLED) self.playerLabel.grid(row=1, column=1) self.p2StringVar = StringVar() self.p2StringVar.set("") self.p2Entry = Entry(self, textvariable=self.p2StringVar, state=DISABLED) self.p2Entry.grid(row=1, column=2) self.hero1Text = Text(self, width=20, height=20, state=DISABLED) self.hero1Text.grid(row=2, column=0) self.heroLabel = Label(self, text="Hero Stats", state=DISABLED) self.heroLabel.grid(row=2, column=1) self.hero2Text = Text(self, width=20, height=20, state=DISABLED) self.hero2Text.grid(row=2, column=2) self.fightButton = Button(self, text="Fight!", state=DISABLED, command=self.fight) self.fightButton.grid(row=3, column=1) # Superhero objects self.p1 = Superhero() self.p2 = Superhero() def startGame(self): self.playerLabel.config(state=NORMAL) self.p1StringVar.set("Superhero 1") self.p2StringVar.set("Superhero 2") self.p1Entry.config(state=NORMAL) self.p2Entry.config(state=NORMAL) self.heroLabel.config(state=NORMAL) self.fightButton.config(state=NORMAL) self.hero1Text.config(state=NORMAL) self.hero1Text.delete(0.0, END) self.hero1Text.config(state=DISABLED) self.hero2Text.config(state=NORMAL) self.hero2Text.delete(0.0, END) self.hero2Text.config(state=DISABLED) # Reset the health and attack points for our super heros self.p1.reset() self.p2.reset() def fight(self): # Disable components self.p1Entry.config(state=DISABLED) self.p2Entry.config(state=DISABLED) self.fightButton.config(state=DISABLED) # Get the names of the heroes self.p1.setName(self.p1Entry.get()) self.p2.setName(self.p2Entry.get()) # display info about each hero self.hero1Text.config(state=NORMAL) self.hero1Text.insert(0.0, self.p1) self.hero1Text.config(state=DISABLED) self.hero2Text.config(state=NORMAL) self.hero2Text.insert(0.0, self.p2) self.hero2Text.config(state=DISABLED) # loop while both players are alive while self.p1.isAlive() and self.p2.isAlive(): # fight self.p1.loseHealthPoints(self.p2.attackValue) self.p2.loseHealthPoints(self.p1.attackValue) # display stats self.hero1Text.config(state=NORMAL) self.hero1Text.insert(END, self.p1.getStats()) self.hero1Text.config(state=DISABLED) self.hero2Text.config(state=NORMAL) self.hero2Text.insert(END, self.p2.getStats()) self.hero2Text.config(state=DISABLED) # Display winner if self.p1.isAlive(): self.hero1Text.config(state=NORMAL) self.hero1Text.insert(END, "\nWINNER!") self.hero1Text.config(state=DISABLED) self.hero2Text.config(state=NORMAL) self.hero2Text.insert(END, "\nDEAD") self.hero2Text.config(state=DISABLED) elif self.p2.isAlive(): self.hero1Text.config(state=NORMAL) self.hero1Text.insert(END, "\nDEAD") self.hero1Text.config(state=DISABLED) self.hero2Text.config(state=NORMAL) self.hero2Text.insert(END, "\nWINNER!") self.hero2Text.config(state=DISABLED) else: self.hero1Text.config(state=NORMAL) self.hero1Text.insert(END, "\nDEAD") self.hero1Text.config(state=DISABLED) self.hero2Text.config(state=NORMAL) self.hero2Text.insert(END, "\nDEAD") self.hero2Text.config(state=DISABLED)
# которые переопределяются дочерним, в данном случае, методом __init__. # Это вызывает конструктор родительского класса: super().__init__(name) # переопределить метод sing def sing(self): return 'Бам, бам, БАМ!' # добавить дополнительный метод экземпляра def boast(self): for power in self.superpowers: print("Я обладаю силой '{pow}'!".format(pow=power)) if __name__ == '__main__': sup = Superhero(name="Тик") # Проверка типа экземпляра if isinstance(sup, Human): print('Я человек') if type(sup) is Superhero: print('Я супергерой') # Получить порядок поиска разрешения метода (MRO), # используемый как getattr(), так и super() # Этот атрибут является динамическим и может быть обновлен print(Superhero.__mro__) # => (<class '__main__.Superhero'>, # => <class 'human.Human'>, <class 'object'>) # Вызывает родительский метод, но использует свой собственный атрибут класса print(sup.get_species()) # => Сверхчеловек
# that are overridden by the child, in this case, the __init__ method. # This calls the parent class constructor: super().__init__(name) # overload the sing method def sing(self): return 'Dun, dun, DUN!' # add an additional class method def boast(self): for power in self.superpowers: print("I wield the power of {pow}!".format(pow=power)) if __name__ == '__main__': sup = Superhero(name="Tick") # Instance type checks if isinstance(sup, Human): print('I am human') if type(sup) is Superhero: print('I am a superhero') # Get the Method Resolution search Order used by both getattr() and super() # This attribute is dynamic and can be updated print(Superhero.__mro__) # => (<class '__main__.Superhero'>, # => <class 'human.Human'>, <class 'object'>) # Calls parent method but uses its own class attribute print(sup.get_species()) # => Superhuman
class Application(Frame): def __init__(self, master): super().__init__(master) self.grid() self.buttonStart = Button(self, text="Start Game", command=self.startGame) self.buttonStart.grid(row=0, column=1) self.entName1 = Entry(self) self.entName1.grid(row=1, column=0) self.labelPrompt = Label(self, text="Enter player names") self.labelPrompt.grid(row=1, column=1) self.entName2 = Entry(self) self.entName2.grid(row=1, column=2) self.textStats1 = Text(self, width=20, height=20) self.textStats1.grid(row=2, column=0) self.labelStats = Label(self, text="Hero Stats") self.labelStats.grid(row=2, column=1) self.textStats2 = Text(self, width=20, height=20) self.textStats2.grid(row=2, column=2) self.buttonFight = Button(self, text="Fight!", command=self.fight) self.buttonFight.grid(row=3, column=1) # create a superhero object and store in frame. Cannot store in main with GUI self.p1 = Superhero() self.p2 = Superhero() def startGame(self): # assign the neames the player has typed to superhero name1 = self.entName1.get() name2 = self.entName2.get() if name1 == "": name1 = "Wonder Woman" if name2 == "": name2 = "Batman" self.p1.setName(name1) self.p2.setName(name2) def fight(self): #show initial stats self.textStats1.insert(0.0, self.p1.getStats()) self.textStats2.insert(0.0, self.p2.getStats()) while self.p1.isAlive() and self.p2.isAlive(): self.p1.loseHealthPoints(self.p2.getAttackValue()) self.p2.loseHealthPoints(self.p1.getAttackValue()) self.textStats1.insert(0.0, self.p1.getStats()) self.textStats2.insert(0.0, self.p2.getStats())