Struggeling with collections
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Mar 7 03:52:53 EST 2016
On Monday 07 March 2016 19:24, Faling Dutchman wrote:
> Hey folks,
>
> I am just starting off in python, but have good knowledge of both Java and
> C#. Now is the problem that I need to have multiple instances of one
> dictionary, that is not a problem if you know how many, but now, it is an
> unknown amount.
Whenever you have an unpredictable number of some object, *any* object, you
should turn to a list, or a dict.
"I need some integers, but I don't know if there will be 3 or 5."
Wrong solution:
a = 23
b = 24
c = 25
if foo:
d = 26
e = 27
# later...
if foo:
print(a, b, c, d, e)
else:
print(a, b, c)
Right solution:
integers = [23, 24, 25]
if foo:
integers.extend([26, 27])
# later...
print(*foo)
It doesn't matter whether you are dealing with ints, floats, strings, dicts,
lists, sets, or your own custom-built objects. If you don't know in advance
how many you want, put them in a list. Or a dict.
> Some background info:
>
> I am making a library for an API. This library must be easy to use for the
> people who are going to use it.
Define "easy to use".
> If I do this:
>
> class Item:
> def __init__(self, id, productId, quantity, pageCount, files, option,
> metadata):
> self.id = id
> self.productId = productId
> self.quantity = quantity
> self.pageCount = pageCount
> self.files = files
> self.option = option
> self.metadata = metadata
>
> itm = Item(1,None,1,1,'asdf',{'asdf': 3, 'ads': 55},None)
> print(itm)
>
> it prints: <__main__.Item object at 0x02EBF3B0>
>
> So that is not usefull to me.
Then create a better __repr__ or __str__ method. All you are seeing is the
default representation inherited from object. If you don't like it, override
it.
--
Steve
More information about the Python-list
mailing list