Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to change dict value, but allert me a Error 'object does not support item assignment'
Full Code:
def __init__(self):
self.dict = dict()
def __getitem__(self, item):
return self.dict[item]
arr = SparseArray()
arr[0] = 1```
You to override __setitem__
def __setitem__(self, key, value):
self.dict[key] = value
Then you'll be able to assign a value using an index
# use of __setitem__
arr[0] = 1
arr["foo"] = 5
# use of __getitem__
print(arr[0]) # 1
print(arr["foo"]) # 5
Also avoid naming variable as built-in name like dict, at least you can use items or values if there is no real sense about the variable's content
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
What I have to do is to create a class that counts from a giving single argument and itself make the arithmetical operation.
class Counts:
def __init__(self, value=0):
self.value = value
def newvalue(self, other):
return Counts(self.value + other)
But for every I make to the code I got any different error, either syntax or callable argument.
The idea is to get
Counts()
Expected output
0
Next
Counts.newvalue(10)
Expected output
10
Next
Counts.newvalue(40)
Expected output
50
Next
Counts.newvalue(-17)
Expected output
33
And so on.
The code that shows the expected behaviour is
class Counts:
value = 0
def __new__(self):
return self.value
#classmethod
def newvalue(cls, other):
cls.value += other
return cls.value
however this is a somewhat strange piece of code, as you are creating a class that returns a value when initialized instead of an object deriving from that class by overriding __new__, which is pretty non-standard.
also if you want to zero the value whenever Count() is called, you can add a self.value = 0 before the return self.value
Tests ->
print(Counts())
print(Counts.newvalue(10))
print(Counts.newvalue(40))
print(Counts.newvalue(-17))
returns
0
10
50
33
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I made a class with some functions:
But when I instantiate the values the answer is bringing me 'alimentos', but that's wrong it should be 'portugues' .
I have two dictionaries and this class:
professores_x = {
'alimentos': [{"prof_id":"xx_alimento_1", "prof_disc":"alimentos"},
{"prof_id":"xx_alimento_2", "prof_disc":"alimentos"}],
'português': [{"prof_id":"xx_port_1", "prof_disc":"português"},
{"prof_id":"xx_port_2", "prof_disc":"português"}]}
courses_x = {'alimentos': [{"course_name":"padeiro_confeiteiro"},
{"course_name":"padeiro_confeiteiro"}]}
# trying refactoring
class Disciplinas_cursos_1:
"Define the disciplinas and professors"
def __init__(self,cursos_,professores_):
self.cursos_ = cursos_
self.professores_ = professores_
for self.p in self.cursos_.keys():
if self.p == 'alimentos': self.alimentos()
elif self.p == 'português': self.portugues()
def alimentos(self):
profiel_prof_disc = self.professores_[self.p][::]
prof_disc_al = self.p
discipl_alimentos = [self.p,[x['prof_id'] for x in profiel_prof_disc
if x['prof_disc'] == prof_disc_al]]
return discipl_alimentos
def portugues(self):
print("Now its portuguese turn")
profiel_prof_disc = self.professores_[self.p][::]
prof_disc_port = self.p
print(f"see I'm printing {prof_disc_port}. It's that the same of portuguese? If' not it's wrong")
discipl_port =[self.p,[x['prof_id'] for x in profiel_prof_disc if x['prof_disc'] ==prof_disc_port]]
print(f"see I'm printing {prof_disc_port} and {discipl_port}")
return discipl_port
# ok!! Now I do the instance:
disc_a = Disciplinas_cursos_1(courses_x, professores_x)
disc_a.alimentos()
Output
['alimentos', ['xx_alimento_1', 'xx_alimento_2']]
Nice, that is what I want but when I try the second function it's bring me 'alimentos'
but I need 'portugues' and not 'alimentos'.
disc_a.portugues()
Output
Now its portuguese turn
see I'm printing alimentos. It's that the same of portuguese? If' not it's wrong
see I'm printing alimentos and ['alimentos', ['xx_alimento_1', 'xx_alimento_2']]
Your issue is with self.p. In __init__, you're setting that value with your loop, and when you call self.alimentos() or self.portugues() in the body of the loop it will make sense since the self.p value will correspond to the method being called.
But if you call disc_a.portugues() from outside of __init__, you're going to get the last value self.p had after the loop, which may not match up at all with the method you're calling. That's why you're getting invalid output, it's using an inappropriate self.p key.
I don't have a firm understanding of what you're intending to do in your methods, so I don't really have a recommended fix. But in general, I'd suggest you think more carefully about which values you're passing to which parts of your code as attributes and as arguments. self.p should probably not exist as an attribute. Maybe it should be an argument to the methods? Maybe you need different attributes to sort your data into separate containers, rather than repeatedly looping over it all. You may need to redesign your class to have its data make more sense the way you need to use it.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
In looping though elements in a python list, I've discovered that it is returning single-valued tuples rather than the underlying values themselves. I'm using Python 3.7.7 to run the following:
class MyClass:
def __init__(self, value):
""" class constructor """
self.value = value,
def __repr__(self):
""" class repr method """
return f'{self.__class__.__name__}(value={self.value!r})'
for val in [14, 20, 21, 48]:
_myclass = MyClass(val)
print(_myclass.value)
Which produces the following output:
(14,)
(20,)
(21,)
(48,)
It is clear that it is passing a single-element tuple to my class constructor instead of the underlying value from the list. I can see the same behavior when I pass the the objects to the print statement:
for val in [14, 20, 21, 48]:
_myclass = MyClass(val)
print(_myclass)
Which produces:
MyClass(value=(14,))
MyClass(value=(20,))
MyClass(value=(21,))
MyClass(value=(48,))
This becomes a problem when I want to work with the value in my class -- in this case, treating it as the expected number (e.g., if value < 30: value = 30) would produce a TypeError. How can I correct this?
you put , near the self.value = value remove it will fine. (Someone mentioned in the comment)
class MyClass:
def __init__(self, value):
""" class constructor """
self.value = value
def __repr__(self):
""" class repr method """
return f'{self.__class__.__name__}(value={self.value!r})'
for val in [14, 20, 21, 48]:
_myclass = MyClass(val)
print(_myclass.value)
# output
# 14
# 20
# 21
# 48
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
This works:
class customList(list):
def __init__(self, liste):
list.__init__(self, liste)
myList = customList([4])
This does not:
from collections import UserList
class customList(UserList):
def __init__(self, liste):
list.__init__(self, liste)
myList = customList([4])
I have read subclassing UserList is preferred over subclassing the build-in list, because of unknown behavior of the latter, but how should I initiate the list in my __init__ when subclassing from UserList?
You should use UserList's constructor to initialize it, instead of list's constructor:
class customList(UserList):
def __init__(self, liste):
super().__init__(liste)
A UserList is a wrapper around its internal data parameter.
from collections import UserList
class customList(UserList):
def __init__(self, liste):
self.data = liste
myList = customList([4])
print(myList) # [4]
myList.append(5)
print(myList) # [4, 5]
The main reason you might want to use a UserList rather than a list as your base class is to access the underlying list as an attribute, which is only really important if you wanted to reassign it for some reason.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have to write a code where table is represented as dictionary, each key is the name of the column name and each value is the list of items in that column from top row to bottom.
I can use dictionary, list or whatever i want. So i decided to use dictionary
But when i test my code, I am getting this weird error :
>diction = {'a' : ['letter of a']}
>my_table = Table()
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
builtins.TypeError: __init__() missing 3 required positional arguments: 'new_dict', 'coloumn_name', and 'coloumn_value'
Can someone help me with this?
class Table():
'''A class to represent a SQuEaL table'''
def __init__(self, new_dict, coloumn_name, coloumn_value):
self._new_dict = new_dict
self._key = coloumn_name
self._value = coloumn_value
def new_dictionary(self):
return self._new_dict
def get_coloumn_name(self):
return self._key
def get_coloumn_value(self):
return self._value
def set_dict(self, new_dict):
'''(Table, dict of {str: list of str}) -> NoneType
Populate this table with the data in new_dict.
The input dictionary must be of the form:
column_name: list_of_values
'''
# assign empty dictionary
self._new_dict = {}
# each key represents a coloumn name and each value is list of items
# that coloumn_name from top row to bottom(coloum_values)
self._new_dict += get_coloumn_name[self._key], get_coloumn_value[self._value]
return
You are getting this error because the __init__() function in your class requires 3 arguments - new_dict, coloumn_name, and coloumn_value - and you did not supply them.