Home » Python » Python programs

Public variables in Python

Python | public variables: In this article, we are going to learn about the public variables in Python with Example.
Submitted by IncludeHelp, on September 09, 2018

By default all numbers, methods, variables of the class are public in the Python programming language; we can access them outside of the class using the object name.

Consider the given example:

Here, we have two variables name and age both are initializing with default values ("XYZ" and 0) while declaring the object using __init__ method.

Later, in the program, outside of the class definition – we are assigning some values ("Amit" and 21) to name and age, that is possible only if variables are public.

Example:

# Python example for public variables 
class person:
	def __init__(self):
		# default values
		self.name = "XYZ"
		self.age = 0

	def printValues(self):
		print "Name: ",self.name 
		print "Age : ",self.age

# Main code 
# declare object 
p = person()
# print
p.printValues();

# since variables are public by default 
# we can access them directly here 
p.name = "Amit"
p.age = 21
# print
p.printValues ();

Output

Name:  XYZ
Age :  0
Name:  Amit
Age :  21


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.