I want to use Python instance as a variable in the method.

Asked 2 years ago, Updated 2 years ago, 103 views

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. Is there a way to use that instance as a variable without using Package?

python method instance variable

2022-09-20 18:56

2 Answers

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.


2022-09-20 18:56

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)


2022-09-20 18:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.