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.

Recommended Answers

All 5 Replies

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.

commented: glad you said it! +14

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?

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)

output-->
Hi Tom my name is a
Hi Tom my name is b
----------------

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

This was not a real thread... I'm going to go cry

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.