python - function and classes, usage of __str__ -


i having issues concerning interaction between functions, methods , have uncertainty of how utilize use of built-in function __str__.

to start of, have class called vara, looks like:

class vara(object):      def __init__(self, kod, namn, pris, butikantal):         self.kod = kod         self.namn = namn         self.pris = pris         self.antal = butikantal 

and have function creats list of object vara klass, looks like:

def mina_varor():    varor_fran_fil = open("varor.txt", "r")   varulista = []   rad in varor_fran_fil:       varje_vara1 = rad       varje_vara2 = varje_vara1.split("/")       varorna = vara(varje_vara2[0], varje_vara2[1], varje_vara2[2], varje_vara2[3])       varulista.append(varorna)    return(varulista) 

now want able access singel object in list typing "kod" object. cant find "kod" in list. seemed strange, tried printning list, , got that:

[<__main__.vara object @ 0x00000000031503c8>, <__main__.vara object @ 0x00000000031507f0>, <__main__.vara object @ 0x0000000003150710>, <__main__.vara object @ 0x00000000031502b0>, <__main__.vara object @ 0x00000000031505f8>, <__main__.vara object @ 0x00000000031504e0>]

i looked up, , seems python cant decide how interpret list. think need __str__ method so, how should make __str__ method if want print like:

name: hat price: 150 quantity: 100 code: 223 

?

issue 1: __str__() not being called when printing container

it's not python can't interpret list, doesn't know how expect displayed.

implement __str__ method if want like

print(varulista[0]) 

something following give expect list entry:

def __str__(self):     s  = "name:    %s\n" % self.namn     s += "price:   %s\n" % self.pris     s += "quantity:%s\n" % self.antal     s += "code:    %s\n" % self.kod 

but if want print(varulista) make sense, you'll have implement __repr__ method, since varulista list , when printing python looks __repr__ method.

but being said, idea of __repr__ able pass eval() , create equivalent object. go 1 of 2 ways:

1. ignore __repr__()/eval() interaction

in case, implement __repr__() want. remember method going called when item in container you're printing, keeping output single line might helpful. know unless unambiguously represent state of object in __repr__() output, won't able recreate equivalent object "down road" using eval().

2. (preferred option, imo) implement __repr__() correctly , don't print containers if don't way looks.

if output like

[item{name:"hat",price:150,quantity:100,code:223},item{name:"shirt",price:450,quantity:10,code:225}] 

is unfriendly because of how had implement __repr()__, don't print containers. in other words, don't use

print(varulista) 

but instead use

for item in varulista: print item 

which call __str__() method defined, human-friendly one.

edit: @bernie's links a great answer @alexmartelli regarding difference between __str__ , __repr__ worth linking twice.


issue 2: being able access list element it's code

you say

now want able access singel object in list typing "kod" object. cant find "kod" in list. seemed strange, tried printning list, , got that:

you have 2 main options here. (1) use dictionary keyed on item code. (2) search through list code using list comprehension. i'm going show (1), because think it's better alternative.

option 1: use dictionary keyed on item code

consider code:

# define convenience function add items dictionary def add_item(d,i): d[i.kod] =  # create new dictionary items = {}  # add items dictionary add_item(items, vara(223, "hat", 150, 100)) add_item(items, vara(225, "shirt", 450, 10)) 

you can access defined item items dictionary follows:

items[223] #<-- "hat" item items[225] #<-- "shirt" item 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -