0

I'm pretty new to Python and was simply wondering instead of this:

class human(object):
  def __init__(self):
    self.name = "bobby"

Can we assign the instance variable 'name' in another def, such as this:

def nameBaby(object):
  self.name = "bobby"

3 Answers 3

2

Yes, you can create new attributes on objects anywhere: in __init__, in other methods of your class, or even in code outside of your class. Good style dictates that you define them all in your __init__ anyway though. It makes it easier to understand the code.

Sign up to request clarification or add additional context in comments.

Comments

2

Yes you can.

>>> class human(object):
    def __init__(self):
        self.name = "bobby"
    def call_me(self):
        self.name = "my name is bobby"


>>> h = human()
>>> h.name
'bobby'
>>> h.name = "new name"
>>> h.name
'new name'
>>> h.call_me()
>>> h.name
'my name is bobby'

Comments

0

The advantage of defining it in __init__() is that you know that'll be called before any other method is, so you avoid the risk of trying to access it before it's been created.

For instance, compare this code which creates the member variable in __init__():

#!/usr/bin/env python

class human(object):
    def __init__(self):
        self.name = '<unnamed baby>'

    def nameBaby(self, name):
        self.name = name

    def getName(self):
        return self.name

kid = human()
print kid.getName()
kid.nameBaby('Bruce')
print kid.getName()

outputting:

paul@thoth:~/src/sandbox$ ./baby1.py
<unnamed baby>
Bruce
paul@thoth:~/src/sandbox$ 

with this code, which does not:

#!/usr/bin/env python

class human(object):
    def __init__(self):
        pass

    def nameBaby(self, name):
        self.name = name

    def getName(self):
        return self.name

kid = human()
print kid.getName()
kid.nameBaby('Bruce')
print kid.getName()

outputting:

paul@thoth:~/src/sandbox$ ./baby2.py
Traceback (most recent call last):
  File "./baby2.py", line 14, in <module>
    print kid.getName()
  File "./baby2.py", line 11, in getName
    return self.name
AttributeError: 'human' object has no attribute 'name'
paul@thoth:~/src/sandbox$ 

You cannot usually control in which order a user might call your class methods and, in general, you shouldn't require your classes to depend on any such order. In circumstances such as those shown above, by creating your member variable in __init__(), your code is robust enough to function correctly regardless of which order the user calls methods in (although it doesn't guarantee you'll actually get anything particularly meaningful, of course).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.