Home > other >  What is the correct way to access class variable inside class method? self.class_variable or class_n
What is the correct way to access class variable inside class method? self.class_variable or class_n

Time:09-17

class Employee:
    location = "south"

    def describe(self):
        print(self.location)
   

Should I use self.class_variable to access class variable inside class method?

class Employee:
    location = "south"

    def describe(self):
        print(Employee.location)

Or rather I should be using class_name.class_variable? Which one is the correct convention? Is there even a difference between the two?

Edit 1: So besides other answers that people have given I have found that if you change self.class_variable, it will change it for just that instance and if you change class_name.class_variable, it will change it for all the current and future instances. Hope that helps.

CodePudding user response:

The difference becomes relevant if you subclass:

>>> class Employee:
...     location = "south"
...     def describe_self(self):
...         print(self.location)
...     def describe_class(self):
...         print(Employee.location)
...
>>> class Salesman(Employee):
...     location = "north"
...
>>> Employee().describe_self()
south
>>> Employee().describe_class()
south
>>> Salesman().describe_self()
north
>>> Salesman().describe_class()
south

since if you subclass, the type of self may not actually be Employee.

CodePudding user response:

Yes there is a difference between the two.

class Employee:
    location = "south"


class EmployeeSelf(Employee):
    def __str__(self):
        return self.location


class EmployeeEmployee(Employee):
    def __str__(self):
        return Employee.location


emp = EmployeeSelf()
emp.location = 'north'
print(emp)

emp0 = EmployeeEmployee()
emp0.location = 'north'
print(emp0)

Have a look at this example. Whilst the identifier self points at the object itself the Employee identifier points to the class.

  • Related