hi guys.
can anyone tell me why this code doesn't work? It doesn't raise any error but neither does it provide the expected results.

my_list= ['a','b']

class my_class:
     def __init__ (self):
         self.name = ' my name is hi'

for a in my_list;
    a = my_class()

a.name() gives and error.

7 Years
Discussion Span
Last Post by pyguy62

Look, not to be harsh or anything, but given you previous posts I think you would be better off reading a book or a wiki or even just a tutorial on Python OOP and maybe Python in general. Really.

Edited by scru: n/a

Votes + Comments
glad you said it!

I'm not trying to be a fully fledged programmer. I'm a hobbyist. So I don't want to buy any books on python. I have however, read a few tutorials on python
(a byte of python, how to think like a computer scientist, parts of the python documentation)... so why doesn't it (the code above) work?

Edited by mahela007: n/a


so why doesn't it (the code above) work?

Why shoud it?
Break it thing down to understand what happends.

>>> class my_class:
	def __init__ (self):
		self.name = ' my name is hi'
>>> a = my_class()  #Class instance
>>> print a
<__main__.my_class instance at 0x011E23F0>
# This only show the class instance and memory location.
# So you see now that your code can not work.

>>> a.name  #call __init__(constructor)
' my name is hi'

>>> my_list= ['a','b']
>>> for x in my_list:
	print a.name, x	
 my name is hi a
 my name is hi b

This dosent make must sense.

Just one way that give a little more sense.
my_list= ['a','b']

class my_class:    
    def __init__ (self, name):
        self.name = name       

a = my_class('Tom')

for x in my_list:
    print 'Hi %s my name is %s' % (a.name, x)

Hi Tom my name is a
Hi Tom my name is b

Edited by snippsat: n/a


OH- MY- GOD!!! The problem's been right under my nose. Thanks for your reply

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.