Reputation: 259
We have a class with some mathematical functions inside
class MyObjects(object):
q=1 #could be any number
def f(x,y):
return q*y+x #could be any mathematical function
Let's say we want to create 100 new objects named like object_1
, object_2
...object_100
of this class and all of them must have a variable q
defined, but defined for each object as q_1
, q_2
... q_100
but we want every time an object is created to increment the value of q like if q=1:
q_1=q+1
q_2=q_1+1
and so on. As displayed previously all objects must use the f(x,y) function of the class named for each object like f_1
, f_2
... f_100
. the number of objects generated is going to be set by the user with input()
and that is the reason i would like to automate this procedure which is very cumbersome to do "by hand" by adding that is something like a hundred objects in the code. So can i automate this procedure? Python begginer, monty python veteran lol. Feel free to edit the question if you can rephrase it in a more precise manner.
Upvotes: 0
Views: 4272
Reputation: 250931
Define a class attribute q
and an instance attribue q
.
And every time a new instance is created the MyObjects.q
will be incremented and that incremented value will be assigned to self.q
class MyObjects(object):
q=0
def __init__(self):
MyObjects.q+=1
self.q=MyObjects.q
def f(self,x,y):
return self.q*y+x
inp=input("Enter number of objects: ")
dic={}
for x in range(1,inp+1):
dic[x]=MyObjects()
output:
>>> dic[1].q
1
>>> dic[2].q
2
>>> dic[3].q
3
>>> dic[1].f(2,5)
7
>>> dic[2].f(2,5)
12
>>> dic[3].f(2,5)
17
Upvotes: 5