Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

private instance attribute python

# Square Class: Define a Square with private instance
class Square:
	def __init__(self, size=0):
      # initialise variables
      self.__size = size
Comment

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 :: python cant remove temporary files 
Python :: generating datafraoms using specific row values 
Python :: pandas show all dataframe method 
Python :: numpy unique axis 
Python :: pandas get attribute of object 
Python :: python basics 
Python :: split a pd dataframe 
Python :: how to add legend on side of the chart python 
Python :: torch.nan_to_num 
Python :: run a for loop in python 
Python :: maximize difference codechef 
Python :: mean pandas 
Python :: key pressed pygame 
Python :: python Sum of all the factors of a number 
Python :: how to concatenate two strings in python 
Python :: how to put space in between list item in python 
Python :: max in python 
Python :: pandas convert string to float 
Python :: how to add hyperlink in jupyter notebook 
Python :: protected class python 
Python :: plot histogram from counts and bin edges 
Python :: append to an array in 1st place python 
Python :: how to print python exception message 
Python :: reversing in python 
Python :: time zone in python 
Python :: urllib_errors 
Python :: next day in python 
Python :: python console 
Python :: call javascript function flask 
Python :: extract specific key values from python dictionary 
ADD CONTENT
Topic
Content
Source link
Name
2+1 =