0

I want to add a list as a Python class instance attribute (i.e. not a class attribute), and then add a class method which will append items to the list.

e.g. we have an Employee class and each employee may have won different awards which will be stored in a list.

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        employeeAwards = []

    def addAward(self, Award):
        employeeAwards.append(Award)

However if do this, I get an "unresolved reference" error on the instance attribute (employeeAwards).

Where should I declare the class instance attribute?

2
  • You want a class method that appends to an instance attribute?! Or do you mean an instance method? Commented Jul 15, 2015 at 12:09
  • self.employeeAwards = [] and then self.employeeAwards.append(Award) Commented Jul 15, 2015 at 12:09

2 Answers 2

3

You need to bind it to self:

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        self.employeeAwards = []

    def addAward(self, Award):
        self.employeeAwards.append(Award)
Sign up to request clarification or add additional context in comments.

Comments

1

I think septi pointed out the correct solution already: bind it to self.

Here's an interesting discussion about class vs instance variables: Every variable (or method) you bind to self is in fact an instance variable.

Class variables would look like this:

class Employee(object):
    employeeAwards = []

    def __init__(self, name, salary):
        ...

1 Comment

This is also a valid answer, but you should be careful when using a list as a class attribute. Pay attention that when using append to the list, you are actually updating the class attribute and not the instance attribute.

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.