Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to declare private attribute in python

class Base:
	def __init__(self):
    	self.__private_attribute = 2 #two underscores before attribute declare it as private
Comment

private attributes python

# Making attributes private
# Naming convention, when want to make attribute private, precede it with two underscores __
# e.g. self.__private_data. Then Python automatically renames it as _ClassName__private_date (name mangling)
# so instance.__private_data will not access this attribute
# but instance._PrivateClass__private_data will still be able to access it. 

class PrivateClass:
    """Class with public and private attributes."""

    def __init__(self):
        """Initialize the public and private attributes."""
        self.public_data = "public"  # public attribute
        self.__private_data = "private"  # private attribute
        

instance = PrivateClass()
instance.public_data
# 'public'

instance.__private_data
# AttributeError: 'PrivateClass' object has no attribute '__private_data'

instance._PrivateClass__private_data
# 'private'

instance._PrivateClass__private_data = 'modified'
instance._PrivateClass__private_data
# 'modified'
Comment

PREVIOUS NEXT
Code Example
Python :: how to convert response to beautifulsoup object 
Python :: python how to remove n from string 
Python :: pylab plotting data 
Python :: python string iterate 3 characters at a time 
Python :: pandas remove whitespace 
Python :: access column pandas 
Python :: How to install a python packagae 
Python :: join python documentation 
Python :: check if string match regex python 
Python :: python curses for windows 
Python :: python run bat in new cmd window 
Python :: django admin readonly models 
Python :: python3.8 
Python :: join tuple to string python 
Python :: dict in dict in python 
Python :: python ternary elif 
Python :: python sort comparator 
Python :: brute force string matching algorithm in python 
Python :: python to linux executable 
Python :: pandas split column into multiple columns 
Python :: Using Lists as Queues 
Python :: progress bar in python 
Python :: pyspark dataframe to dictionary 
Python :: download files from url in flask 
Python :: pandas aggregate dataframe 
Python :: how to use sort in python 
Python :: change order of barh matplotlib 
Python :: difference between set and list in python 
Python :: how to delete record in django 
Python :: python get audio from video 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =