bzrr
bzrr

Reputation: 1530

Can attributes be assigned anywhere within a class?

Can attributes be assigned anywhere within a class? If so, how do scope rules works for each of the following cases?

class GreatComposers(object):
    def __init__(self, name, birthday, instrument):

        # attributes assigned in __init__
        self.name = name
        self.birthday = birthday
        self.instrument = instrument

    def setFullName(self)

        # attributes assigned in other class methods
        self.fullname = self.name + self.birthday
        self.job = self.instrument + 'ist'


    # attributes assigned outside any functions
    self.nationality = 'german'

Upvotes: 0

Views: 174

Answers (3)

James Robert Albert
James Robert Albert

Reputation: 424

assigning self attributes outside of init goes against PEP 8, but you can still do it. self.nationality shouldn't work though because self isn't defined. Even if you found a work around it, I wouldn't recommend doing that.

edit: My mistake. I was confusing a pylint warning with pep 8 style. But still, don't do it.

Upvotes: 0

schesis
schesis

Reputation: 59148

Try it and see:

composers.py

class GreatComposers(object):
    def __init__(self, name, birthday, instrument):

        # attributes assigned in __init__
        self.name = name
        self.birthday = birthday
        self.instrument = instrument

    def setFullName(self):  # <<< added missing colon

        # attributes assigned in other class methods
        self.fullname = self.name + self.birthday
        self.job = self.instrument + 'ist'


    # attributes assigned outside any functions
    self.nationality = 'german'
>>> import composers
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "composers.py", line 1, in <module>
    class GreatComposers(object):
  File "composers.py", line 17, in GreatComposers
    self.nationality = 'german'
NameError: name 'self' is not defined

The traceback tells you that, outside a method, you can't assign anything to self.nationality because self doesn't exist (remember that self is just an argument like any other; it's not like this in javascript).

Inside a method, you can do what you like, and PEP 8 doesn't warn against defining instance variables outside __init__(), but your code will be easier to follow if you don't.

Upvotes: 1

user395760
user395760

Reputation:

No, it doesn't work at class scope (self.nationality = 'german' in your example), as there is no name self in scope at this point. And it doesn't work in the other cases because methods or the self parameter are somehow special. Attributes can be assigned anywhere you have a reference to the object. That includes methods, but also all other code that has access to the object in question.

Upvotes: 2

Related Questions