This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Should I use instance or class attributes if there will only be one instance? [closed]
(4 answers)
Closed 7 years ago.
In Python 3, I have a list of classes, and each class has a list in it. I'm having difficulties updating those lists. As so:
class Item():
newPrice = 0
prices = [0]
def __init__(self, _prices):
self.prices = _prices
items = [Item([10]), Item([20]), Item([30])]
for item in items:
item.newPrice = SomeFunction()
item.prices.append(item.newPrice)
The function SomeFunction() is an elaborate function that retrieves a different value for each Item instance.
For some reason, each Item instance in the items list has the same value for prices, which is a list that contains the newPrice value for each Item instance. I hope this is clear enough.
What am I missing?
You should define prices as instance attribute, instead of class attribute, because class attributes are shared between all instances:
class Item():
def __init__(self, _prices):
self.newPrice = 0
self.price = _prices
Related
This question already has answers here:
Pass a list to a function to act as multiple arguments [duplicate]
(3 answers)
How to pass list elements as arguments
(1 answer)
Is there a way to create a class instance passing to the constructor a list of attributes? [duplicate]
(1 answer)
Closed 3 months ago.
I'm currently try to pass the items of a list create an instance of a class.
My code looks like this
args = ["1", "John", "Doe"]
class Token:
def __init__ = (self, id, name, last_name)
self.id = id
self.name = name
self.last_name = last_name
instance1 = Token(args)
I get the error
TypeError: Token.__init__() missing 3 required positional arguments:
I tried changing the type, the data I received comes from a previous for loop that filters the data I need.
Expecting
To create an instance with the values of the list and pass them as args.
Note
The topple is currently in order
Use the iterable unpacking operator:
Token(*args)
This question already has answers here:
python: class attributes and instance attributes
(6 answers)
Closed 1 year ago.
I have a bunch of objects in a list that have a field called "number". Let the list be called "collected".
How would I find the object in the list that has "4" in its field?
I tried
class stats:
def __init__(self, numba):
self.Number = int(numba)
if (collected.Number == 4):
#do stuff
However, I get an error that says
'list' object has no attribute 'number' And even if this worked, how would I be able to see which index of the list has even found the "4"?
Do you mean:
def findindex(lst,value):
for i,n in enumerate(lst):
if n.Number == value:
return i
return -1
If stats is a list containing instances of Data then the stats list doesn't have a Number attribute, the elements do.
stats[i].Number would be legal, for any i in range(len(stats)).
This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 4 years ago.
I tried to create two objects that both have their own inventories.
As far as I'm concerned I successfully managed to create two different objects called my_bag and toms_bag
This is the code I used
class bag(object):
def inventory_add(self, item):
self.inventory.append(item)
inventory = []
bags = [] #List of all bags
#Create bags
my_bag = bag()
my_bag.inventory_add("pencil")
bags.append(my_bag)
toms_bag = bag()
toms_bag.inventory_add("book")
bags.append(toms_bag)
for bag in bags: #Print inventories
print(bag, bag.inventory)
This is the result I get.
<__main__.bag object at 0x004D0830> ['pencil', 'book']
<__main__.bag object at 0x004D0790> ['pencil', 'book']
So why are the items added to both of their inventories? Are they even different objects now?
Your syntax looks like you're coming from C#, Java, C++, or some other more strictly OOP language. The way to do what you want in Python is to initialize the inventory array in the class constructor:
class bag(object):
def __init__(self):
self.inventory = []
def inventory_add(self, item):
self.inventory.append(item)
This question already has answers here:
python: class attributes and instance attributes
(6 answers)
Closed 8 years ago.
I have a simple question:
Say that I have the following class:
class step:
alpha = []
and my main has the following:
listofstep = []
for i in range(20):
z = step()
z.alpha.append(0)
listofstep.append[z]
why does len(listofstep[0].alpha) gives me 20?
As you define it, alpha is a class variable and not an instance variable. When you do z.alpha it always points at the same list, regardless of which instance it is. Try to define step like this:
class step:
def __init__(self):
self.alpha = []
This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 9 years ago.
I have the following code:
import math
class h:
vektor = [0,0]
rel_chyba = 0
def __init__(self, hodnota, chyba):
self.vektor[0] = hodnota
self.vektor[1] = chyba
self.rel_chyba = chyba*1.0/hodnota
def __rmul__(self, hod2):
return h(hod2.vektor[0]*self.vektor[0], math.sqrt(self.rel_chyba*self.rel_chyba+hod2.rel_chyba*hod2.rel_chyba))
v = h(12,1)
print v.vektor[1]
t = h(25,2)
print v.vektor[1]
My problem is, that v.vektor[1] prints 1 for the first time and 2 for the second time. All the attributes of the object v are assigned the values of the attributes from t.
How can I create two different objects?
Thanks for your answers
Don't declare vektor at class level, that makes it a class variable. Just declare it inside __init__:
def __init__(self, hodnota, chyba):
self.vektor = [hodnota, chyba]