zou zou - 6 months ago 13
Python Question

Understanding classes 'self'

I was reading something about classes, I saw this example.

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))


My questions is,
employee
is not in
__init__
part but we used it as
self.employee.append()
in
add_employee
function. Why is that? Why we used
self.employee.append()
instead of
employee.append()
? I thought we only have to use
self
if a variable is in
__init__
part.

Answer

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
Comments