If you answer my question, I will never forget this kindness. My question is, to sum up,
I want to use the instance as a variable in the method.
For example,
class Marine:
def __init__(self):
self.health = 40
self.power = 15
def attack(self, unit):
unit.health -= self.power
The print ("{}" was attacked and blood became {}. (Attack power of {})"format(unit, unit.health, self, self.power))
marine_1 = Marine()
marine_2 = Marine()
marine_1.attack(marine_2)
Expected result value of =
marine_2 was attacked and blood became 25. (Marine_1's attack power 15)
Actual Result Value =
<__main__.Marine object at 0x7fc5f0085d60> was attacked, resulting in 25 blood. (<__main__.Marine object at 0x7fc640a6f760>Attack power 15)
How can marine_2 be used as a variable in the attack method?
-. I don't want to use aguments.
def __init__(self, name):
self.name = name
(Optimized)
The print ("{}" was attacked and blood became {}. (Attack power of {})"format(unit.name, unit.health, self.name, self.power))
marine_2 = Marine("marine_2")
I don't want to use it like this
marine_2 = Marine()
I want to use marine_2
-. However, I prefer to add a method.
-. I tried to put all the attributes in dir(marine_2) such as print(marine2.main)/print(marine_2.main), but there was no result of returning "marine_2" only with the address.
The variable name in the source is just a symbol. The variable name should be a meaningful symbol only for the programmer who writes the source, and it is strange to use the name as actual data.
I don't know why I don't want to use it like marine_2 = Marine("marine_2")
and I think it's the right way to use it explicitly.
Due to the nature of the dynamic interpreter language, there may be a way to find out the variable name, but it's too unnatural.
Please refer to the code below.
class Marine:
marine_id = 0
def __init__(self):
Marine.marine_id += 1
self.health = 40
self.power = 15
self.name = 'marine_' + str(Marine.marine_id)
def attack(self, unit):
unit.health -= self.power
The print ("{}" was attacked and blood became {}. (Attack power of {})"format(unit.name, unit.health, self.name, self.power))
marine_1 = Marine()
marine_2 = Marine()
marine_3 = Marine()
marine_1.attack(marine_2)
marine_3.attack(marine_2)
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
574 Who developed the "avformat-59.dll" that comes with FFmpeg?
582 PHP ssh2_scp_send fails to send files as intended
619 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.