954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Why doesn't this work? (creating objects from a list)

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.

mahela007
Posting Whiz in Training
214 posts since Feb 2009
Reputation Points: 16
Solved Threads: 2
 

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.

scru
Posting Virtuoso
1,629 posts since Feb 2007
Reputation Points: 975
Solved Threads: 140
 

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?

mahela007
Posting Whiz in Training
214 posts since Feb 2009
Reputation Points: 16
Solved Threads: 2
 
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
----------------
snippsat
Practically a Posting Shark
808 posts since Aug 2008
Reputation Points: 353
Solved Threads: 294
 

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

mahela007
Posting Whiz in Training
214 posts since Feb 2009
Reputation Points: 16
Solved Threads: 2
 

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

pyguy62
Posting Whiz
353 posts since Aug 2011
Reputation Points: 34
Solved Threads: 19
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You