

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are public and private variables in Python class?
Public Variables
Python doesn’t restrict us from accessing any variable or calling any member method in a python program.
All python variables and methods are public by default in Python. So when we want to make any variable or method public, we just do nothing. Let us see the example below −
Example
class Mug: def __init__(self): self.color = None self.content = None def fill(self, beverage): self.content = beverage def empty(self): self.content = None brownMug = Mug() brownMug.color = "brown" print brownMug.empty() print brownMug.fill('tea') print brownMug.color print brownMug.content
All the variables and the methods in the code are public by default.
When we declare our data member private we mean, that nobody should be able to access it from outside the class. Here Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into _<className><memberName> . So to make our member private, let’s have a look at the example below −
Example
class Cup: def __init__(self, color): self.__content = None # private variable def fill(self, beverage): self.__content = beverage def empty(self): self.__content = None
Our cup now can be only filled and poured out by using fill() and empty() methods. Note, that if you try accessing __content from outside, you’ll get an error. But you can still stumble upon something like this −
redCup = Cup("red") redCup._Cup__content = "tea"
- Related Questions & Answers
- What are private, public, default and protected access Java modifiers?
- Are the private variables and private methods of a parent class inherited by the child class in Java?
- Private Variables in Python
- What are class variables, instance variables and local variables in Java?
- What are the differences between public, protected and private access specifiers in C#?
- Private Variables in Python Program
- Difference between Private and Public IP addresses
- Difference between Private Key and Public Key
- Difference between private, public, and protected modifiers in C++
- Difference between private, public, and protected inheritance in C++
- Private Variables in C#
- What are cryptography, symmetric and public key algorithms?
- What are variables and types of variables in C++?
- What are local variables and global variables in C++?
- Does Python have “private” variables in classes?