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

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 :: install easygui conda 
Python :: add option in python script 
Python :: cufflink install python jupyter 
Python :: python set timezone windows 
Python :: perform_update serializer django 
Python :: python lambda function if else 
Python :: string in list python 
Python :: duplicates in python list 
Python :: how to plot in python 
Python :: spanish to english 
Python :: deep clone 2d list python 
Python :: code for merge sort 
Python :: python print date, time and timezone 
Python :: defaultdict initialize keys 
Python :: make venv 
Python :: pythagorean theorem python 
Python :: uses specific version python venv 
Python :: power of array 
Python :: csv download django 
Python :: python generate string 
Python :: python recursion factorial 
Python :: sns boxplot 
Python :: permutation python 
Python :: how to make tkinter look modern 
Python :: empty list in python 
Python :: python expand nested list 
Python :: find nan values in pandas 
Python :: check multiple keys in python dict 
Python :: turtle 
Python :: If elif else 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =