Answers for "python class private attribute"

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

Code answers related to "python class private attribute"

Python Answers by Framework

Browse Popular Code Answers by Language