Whats The Difference


Recommended Posts

I am slowly absorbing these python class concepts(kinda)

this fails with an error

class Critter(object):

   def __init__(self):
       print "I am born"
       

   def talk(self,name):
       self.test = name
       print self.test

crit = Critter('ralph')
crit.talk()

this one works

class Critter(object):

   def __init__(self,name):
       print "I am born"
       self.test = name
       print self.test    

   def talk(self):
       print 'ya'
     

crit = Critter('ralph')
crit.talk()

this seems that the parameter 'ralph' can only be passed to the __init__ method, but not the talk method. Is that a correct assumption, if so why?

Link to post
Share on other sites
....this fails with an error

class Critter(object):
   def __init__(self):
       print "I am born"
   def talk(self,name):
       self.test = name
       print self.test
crit = Critter('ralph')
crit.talk()

this one works

class Critter(object):
   def __init__(self,name):
       print "I am born"
       self.test = name
       print self.test    
   def talk(self):
       print 'ya'
crit = Critter('ralph')
crit.talk()

this seems that the parameter 'ralph' can only be passed to the __init__ method, but not the talk method. Is that a correct assumption, if so why?

<{POST_SNAPBACK}>

The first piece of code works, just put your 'ralph' where your talk is.... like so

class Critter(object):
   def __init__(self):
       print "I am born"
   def talk(self,name):
       self.test = name
       print self.test
crit = Critter()
crit.talk('ralph')

Link to post
Share on other sites

Thanks :-)

it seems that any parameters given directly to the object are passed only to the __init__ constructor(for the most part)

@jcl

you kind of already answered this for me before, but I was still not sure

Edited by shanenin
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...