-1

In the following example employee is not used in the __init__ function, but we used it in the add_employee function calling self.employee.append(). Why is that? Why did we use self.employee.append() instead of employee.append() ? I thought we only use self for variables in the __init__ function.

class Workers():
    employee = []

    def __init__(self, name):
        self.name = name
        self.skills = []
        self.add_employee()

    def add_employee(self):
        self.employee.append(self.name)
        print('{} added to list'.format(self.name))
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
zou
  • 1
  • 1

2 Answers2

1

employee, __init__, and add_employee are just attributes of the class Workers.

employee is an attribute being a list, and __init__ is another attribute, being a method.

Also from the [def documentation]( https://docs.python.org/3/reference/compound_stmts.html#grammar-token-funcdef):

A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function).

so employees and __init__ and all other methods are really the same: names in a namespaces.

See also https://docs.python.org/3/tutorial/classes.html#class-objects

Julien Palard
  • 8,736
  • 2
  • 37
  • 44
0

The employee object is a class variable, not an instance variable. This means it is shared across all instances of that class. You can access it with classname.classvariablename or instancename.classvariablename. If you reassign an instance's version of it with something like instancename.classvariablename = newvalue, that instance will have a new instance variable of that name that masks its access to the class variable with the self reference (i.e., you won't be able to do instancename.classvariablename to get the class variable), but other instances - and the class - will still be able to (i.e., classname.classvariable will still work, and otherinstancename.classvariable will still point to that class variable). The following example demonstrates this.

>>> class A:
...     l = []
...
>>> a = A()
>>> b = A()
>>> a.l
[]
>>> A.l
[]
>>> a.l = 3
>>> b.l
[]
>>> b.l.append(1)
>>> b.l
[1]
>>> A.l
[1]
>>> a.l
3
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97