I'm new to classes and to the python module ObjectListView. I wish to create a text-editable window using ObjectListView, but the example I'm basing my work on requires the objects which each define text entries of a multi-columned row, should be accessible in a list such as this:
names = [MyClass("James", "Cameron"), MyClass("Samantha", "Jones")]
(Note that quotation marks only bookend the first name and surnames of each entry).
I currently hold my names in a standard dictionary which is in this format:
namesDict = { "James":"Cameron", "Samantha":"Jones"}
My attempt to convert my dictionary into the format required is here:
namesDict = { "James":"Cameron","Samantha":"Jones"}
out = []
for key in namesDict:
out.append("MyClass(\""+key+"\",\""+namesDict[key]+"\")")
print(out)
My code leaves me with the following product, which is all good EXCEPT for the single quotation marks around each entry in the list:
['MyClass("James","Cameron")','MyClass("Samantha","Jones")']
I'm not sure how to get rid of these single quotes. I'm also assuming that there may be a standard technique to make objects from dictionaries which I'm simply not aware of?
The quote marks indicate that you're dealing with string literals, as that's what you've passed to the out list. Assuming your MyClass
constructor takes two arguments, you can add an instance to your list like:
out.append(MyClass(key, namesDict[key])
However, this won't print the way you expect, it will use the object.__str__
which returns object.__repr__()
:
<__main__.MyClass object at 0x000002571A58B400>
You can override this in your class:
class MyClass:
def __init__(self, first, last):
self.first = first
self.last = last
def __str__(self):
return self.__class__.__name__ + '("' + '","'.join([str(v) for k,v in vars(self).items()]) + '")'
And then the instances of MyClass
will be printed neatly:
>>> m = MyClass('James','Cameron')
>>> print(m)
MyClass("James", "Cameron")