Tutorial Example

Only Permmit Python Update Class Variable Value by Instance Method – Python Tutorial

In python class, we can create some variables. We also can update their value as follows:

obj_instance.attribution = value

Here obj_instance is python class instance, attribution is a variable in python class. For example:

class Person(object):
 
    def __init__(self):
        self.name = "Lily"
p = Person()
print(p.name)
p.name = 'Tom'
print(p.name)

In this example, we have created a Person instance p, we update name variable value as follows:

p.name = 'Tom'

Run this code, we will get this result:

Lily
Tom

How to update python class variable value only by its method?

If you do not want to update person name by:

p.name = 'Tom'

And only allow to use a class method to update, you can do like this:

Create a variable starting with “__“, this variable will be a private variable for class Person.

For example:

class Person(object):
 
    def __init__(self):
        self.__name = "Lily"
 
p = Person()
print(p.__name)

Run this code, you will get this error:

AttributeError: ‘Person’ object has no attribute ‘__name’

How about we set the value of __name?

Look at this example:

class Person(object):
 
    def __init__(self):
        self.__name = "Lily"
 
p = Person()
p.__name = 'Tom'
print(p.__name)

Run this code, youi will find the result is:

Tom

Have we updated the value of __name variable in Person?

Look at this example:

class Person(object):
 
    def __init__(self):
        self.__name = "Lily"
    def printName(self):
        print(self.__name)
 
p = Person()
p.__name = 'Tom'
print(p.__name)
p.printName()

Run this code, you will get this result:

Tom
Lily

We can find p.__name = ‘Tom’ does not update the value of __name variable in Person. It only adds a __name property for variable p.

We print all properties of p as below:

class Person(object):
 
    def __init__(self):
        self.__name = "Lily"
    def printName(self):
        print(self.__name)
 
p = Person()
print(dir(p))
p.__name = 'Tom'
print(p.__name)
p.printName()
print(dir(p))

Run this code, we can find:

__name is added to variable p.

Where is __name in class Person?

Look at this image below:

How to update __name value?

There are two methods:

Method 1: Use _Person__name

Here is an example:

p._Person__name = 'John'
p.printName()

Method 2: Create a function in Person class to update __name

Here is an example:

class Person(object):
 
    def __init__(self):
        self.__name = "Lily"
    def printName(self):
        print(self.__name)
    def updateName(self, n):
        self.__name = n
p.updateName('John')
p.printName()

Run this code, __name will be updated to “John