Advertisement
# Python - Direct access of a static variable using the name of its class
class Test:
#Defining two class variable/static variables of class Test
n = 10
message = 'Have a good day!'
# Accessing a static variable, n, using its class name with a dot operator
print(Test.n)
# Accessing a static variable, message, using its class name with a dot operator
print(Test.message)
10
Have a good day!
# Python - Direct access of a static variable using the object of its class
class Test:
#Defining two class variable/static variables of class Test
n = 10
message = 'Have a good day!'
# Creating an object of a class
ob = Test()
# Accessing a static variable, n, using its class name with a dot operator
print(Test.n)
# Accessing a static variable, message, using the object of the same class with a dot operator
print(ob.message)
10
Have a good day!
Advertisement
# Direct access of a static variable
class Test:
#Defining a class variable/static variable with an int value 10
n = 10
# Defining a method
def method(self):
# Accessing the static variable within this general method using its class name
print(Test.n)
# Accessing the static variable from within this general method using self keyword i.e. current object.
# In this case, an object name is internally replaced by its class name while calling a static variable
print(self.n)
# self.n =10 would have not modified the static variable to 10
# but would've rather created an instance variable with the same name
# Calling the constructor to create an object of class
ob1 = Test()
# Calling the method() associated with the object, ob1
ob1.method()
# Accessing the value of a static variable using the object name
print(ob1.n)
#Printing the value of static variable of the class using the class name
print(Test.n)
10
10
10
10
# Direct access of a static variable
class Test:
#Defining a class variable/static variable with an int value 10
n = 10
# Defining a method
def method(self):
# Defining an instance variable with the same name as the static variable i.e. 'n'
self.n = Test.n + 10
# Calling the constructor to create an object of class
ob1 = Test()
# Calling the method() associated with the object, ob1
ob1.method()
# Accessing an instance variable, n, has overshadowed the static variable with the same name
# Hence, trying to access the static variable using the object name gives us instance variable.
print(ob1.n)
# Accessing the value of static variable of the class using the class name
print(Test.n)
20
10
class Test:
#Defining a class variable/static variable with an int value 10
n = 10
# Directly accessing the static variable will lead to an error
print(n)
Traceback (most recent call last):
File "D:/Python Programs/static7.py", line 7, in <module>
print(n)
NameError: name 'n' is not defined
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement