This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
I have a class and I want to create dynamically instances of that class. I don't know the exact number of instances so that I dont want to create that classes by a known variable like this:
class Person:
def __init__(self, age, gender):
self.age=age
self.gender=gender
P1=Person(23, "M")
P2=Person(64, "F")
P3=Person(12, "M")
I am looking for sth like
i=0
maxPopulation=10
while i< maxPopulation:
Person(randomx, randomy)
i+=1
But that way I don't know how to access the instances. During the runtime.
I am not looking for a random function.
Add them to a list.
i=0
maxPopulation=10
people = []
while i< maxPopulation:
people.append(Person(randomx, randomy))
i+=1
Or, cleaned up a bit to be more Pythonic:
maxPopulation=10
people = []
for _ in range(maxPopulation):
people.append(Person(randomx, randomy))
Or even more Pythonic:
max_population = 10
people = [Person(randomx, randomy) for _ in range(max_population)]
Related
This question already has answers here:
How to change a module variable from another module?
(3 answers)
Closed last year.
I have this module which stores a class, an instance of that class, a counter, and a dictionary:
#test_module.py:
class TestClass:
def __init__(self, name='name', attr='attr'):
self.name = name
self.attr = attr
def func(self, test_list):
test_dict[count] = test_list[-1].name + '_' + test_list[-1].attr
test_inst = TestClass()
count = 0
test_dict = {}
What I want is for the dictionary to store each consecutive value of the counter (1,2,3...) as a key and the name and attribute of the last class instance in a test_list. (All the code here is simplified for the sake of reproducing the problem, the actual number of classes and instances is greater).
In a notebook, I have the following code:
from test_module import *
test_list = []
test_list.append(test_inst)
count += 1
test_list_item = test_list[-1]
test_dict[count] = test_list_item.name + '_' + test_list_item.attr
test_list.append(test_inst)
count += 1
test_list_item = test_list[-1]
test_list_item.func(test_list)
What now is in the dictionary is:
{1: 'name_attr', 0: 'name_attr'}
Why am I getting zero as the second key?
I've tried specifying the count and the test_dict as global variables in the TestClass definition, but to no avail.
All works OK if I copy the contents of the test_module into the notebook, but this is not what I'm after. My goal is to have as much code as possible in the test_module. What am I doing wrong? How can I make it work properly?
I just copied your code and the output is
{1: 'name_attr', 2: 'name_attr'}
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
I want to see if there is a better way. I am kinda new to python. It is a way for me to try and use classes. Any help or suggestions would be nice.
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '#company.com'
for Number in range(30):
globals()[f"E{Number}"] = Employee('First', 'Last', 0)
print(E5.__dict__)
If you want a collection of instances, don't use individually named variables; use a container like a list
Es = [Employee('First', 'Last', 0) for _ in range(30)]
or a dictionary
Es = {k: Employee('First', 'Last', 0) for k in range(30)}
In both cases, you can index Es with an int; a dict gives you more flexibility in terms of what kinds of indices to use instead.
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I have some list like:
all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]
And I want to print it out like
num = 0
print(all+num)
But it didn't work.
How to add a character or a number to a variable name?
Hmm, I am pretty sure that you do not need nor really want it, but Python has provision for computing a variable name. Simply it is a rather advanced feature and the normal way is to use mappings (dict) or sequence (list or tuple) containers.
Here, you would use:
all = []
all.append([['mortem' 'cliffi' 'gear' 'lerp' 'control']])
all.append([['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']])
num = 0
print(all[0])
BTW, this syntax is weird, because you are essentially concatenating adjacent litteral string...
But if you really, really need it you can build a interpolator of variables:
def getvar(name):
if name in locals():
return locals()[name]
elif name in globals():
return globals()[name]
else:
raise NameError(repr(name) + ' is not defined')
You can then do:
all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]
num = 0
print(getvar("all%d" % num))
and get as expected:
[['mortemcliffigearlerpcontrol']]
You can use eval() for that.
eval('print(all{})'.format(num))
But this is really bad style. Don't do this. You should refactor your code and use for loops to go through your lists e.g.
all = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all.append(['video' 'player' 'stori' 'book' 'think' 'narr' 'kill'])
for l in all:
print(l)
Leaving aside how bad an idea it might be (probably really bad), variable names are just keys in a Python dict. A one-line solution might be:
vars()[new_name] = vars().pop(old_name)
for global variables, and
vars(some_obj)[new_name] = vars(some_obj).pop(old_name)
for variables of some_obj object.
This question already has answers here:
python class instance variables and class variables
(4 answers)
Closed 5 years ago.
I came across some rather strange behavior.
class Example:
test = []
def __init__(self):
print(self.test)
self.test.append(0)
ex1 = Example()
ex2 = Example()
ex3 = Example()
I'd expect this to output [] every time, however, I get:
[]
[0]
[0, 0]
What is this wizardry? Could you help me understand?
Thank, you!
Edit:
Hey, thank you for the quick answers.
Just to clarify, if "test" is static then why do I not notice this behavior when I replace "self.test.append(0)" with "self.test = [0]"?
test is a static class attribute, which you are continually updating with values. Python is different from some other languages in this way. To make it an object attribute, use self.test = [] in your constructor.
test there is a class-level static variable, which is shared between the instances of the class.
You'll want to initialize test within the __init__ method.
class Example:
def __init__(self):
self.test = []
print(self.test)
self.test.append(0)
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 years ago.
I'm trying to store the result of random.random into a variable like so:
import random
def randombb():
a = random.random()
print(a)
randombb()
How can I properly get a?
Generally, you return the value. Once you've done that, you can assign a name to the return value just like anything else:
def randombb():
return random.random()
a = randombb()
As a side note -- The python tutorial is really great for anyone looking to learn a thing or two about the basics of python. I'd highly recommend you check it out. Here is the section on functions: https://docs.python.org/2/tutorial/controlflow.html#defining-functions ...
You can make it a global variable if you don't want to return it. Try something like this
a = 0 #any value of your choice
def setavalue():
global a # need to declare when you want to change the value
a = random.random()
def printavalue():
print a # when reading no need to declare
setavalue()
printavalue()
print a
You can simply store the value of random.random() as you are doing to store in a, and after that you may return the value
import random
def randombb():
a = random.random()
print(a)
return a
x= randombb()
print(x)