I have a class that I'm gonna write more variables to. I successfully use the information in it, and change information in it, but I can't find a way to make new variables. I want to use c
in add_unit_group()
to define both name of the new variable, and its list. I have tried using c
to only define the name of the variable as well, but with no luck.
To the UnitGroups
class, I want to add: a2 = ("default", unit_type)
import units
unit_type = (units.Tank1, units.Tank2, units.Tank3, units.Infantry1, units.Infantry2)
class UnitGroups:
a = "empty"
a1 = ("default", unit_type)
create = "1"
def addunitgroup():
add = ("default", unit_type)
# UnitGroups.create = add
for make in range(0, 10):
if make is int(UnitGroups.create):
print(def_name, ": ", "make is UnitGroups.create")
generate = UnitGroups()
a = (int(UnitGroups.create) + 1)
b = "a" + str(a)
c = str("generate." + b + " = " + str(add))
# UnitGroups.a = (c, " = ", str(add))
# exec(str(UnitGroups.a))
# UnitGroups.a2 = add
UnitGroups.create = (int(UnitGroups.create) + 1)
UnitGroups.a = "empty"
if __name__ == "__main__":
addunitgroup()
I do not want to change the format. The variables shall be stored in that class.
Outcome that I want after first use of "addunitgroup()"
class UnitGroups:
a = "empty"
a1 = ("default", unit_type)
a2 = ("default", unit_type)
create = "2"
Outcome that I want after second use of "addunitgroup()"
class UnitGroups:
a = "empty"
a1 = ("default", unit_type)
a2 = ("default", unit_type)
a3 = ("default", unit_type)
create = "3"
More information, just to show how I currently change the variables inside the class. I don't need help with what's added now: This load()
function will change, and will also set the variables' values depending on what a file tells it to. I'll also use another function to set the values of the variables. This one will be run from a window.
def load():
UnitGroups.a1 = ("5", units.Tank1)
use setattr(instance, variable_name, variable_value)
Btw: the way you have defined your class, the variables belong to the class itself, not the instance (roughly like static variables in other languages)
class B:
def __init__ (self):
self.a = []
def add (self, value)
self.a.append (value)
b = B () # Constructor __init__ calles, will make empty list inside b
b.add ('john') # Will be in b.a [0]
b.add ('mary') # Will be in b.a [1]
b2 = B () # Another instance, to hold different names
b.add ('bjarne') # Will be in b2.a [0]
b.add ('guido') # Will be in b2.a [1]
etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.