Use class_name dot variable_name to access a class variable from a class method in Python. Use instance to access variables outside the class.
Example access a class variable in Python
Simple example code.
A class variable is a variable that is shared by all objects of the same class.
class Employee: branch = 'IT Branch' # Class Variable def a_class_method(): print(Employee.branch) Employee.a_class_method()
How to access variables from a class in python
Print variable values.
class Example(object): msg = "Hello" obj = Example() print(obj.msg) print(Example.msg)
Accessing class variables outside the class in Python
First, you need to create an instance of the class, then you can use that instance to access its instance variable and function.
class Example(object): var_msg = "Welcome" var_num = 100 obj_example = Example() print(obj_example.var_msg) print(obj_example.var_num)
Do comment if you have any doubts or suggestions on this Python variables tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.