private instance attribute python
# Square Class: Define a Square with private instance
class Square:
def __init__(self, size=0):
# initialise variables
self.__size = size
private instance attribute python
# Square Class: Define a Square with private instance
class Square:
def __init__(self, size=0):
# initialise variables
self.__size = size
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)
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us