Answers for "private attributes in python"

1

private instance attribute python

# Square Class: Define a Square with private instance
class Square:
	def __init__(self, size=0):
      # initialise variables
      self.__size = size
Posted by: Guest on June-01-2021
1

how to make class attribute private in python

# To make an attribute of a class private, use two underscores as the first two characters of the attribute name.

class Student:
    def __init__(self, name, id):
        self.name = name
        self.__id = id

    def showInfo(self):
        print(self.name)
        print(self.__id)

s = Student("Alice", 1234)

# This will work, because name is a public attribute, __id is private and it is accessed from inside the class.
s.showInfo()

# This will work, because name is a public attribute
print(s.name)

# This will not work, because __id a private attribute of the class, so it cannot be accessed outside of the class.
print(s.__id)
Posted by: Guest on July-19-2021
1

how to declare private attribute in python

class Base:
	def __init__(self):
    	self.__private_attribute = 2 #two underscores before attribute declare it as private
Posted by: Guest on July-24-2021

Code answers related to "private attributes in python"

Python Answers by Framework

Browse Popular Code Answers by Language