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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.