Private and Public Concepts
Encapsulation provides access to the methods and attributes of the class.
Private or public
Some attributes and/or methods cannot be accessed or modified. For example, it is correct not to change the number_of_legs
of your cat
object (usually, this value is 4).
This attribute must be private - not available outside the class.
By default, all methods and attributes are public in the Python class.
To make it private, add two __
before the variable name:
12345678class Cat: def __init__(self, name = 'Kitty', age = 1): self.name = name self.age = age # Private self.__number_of_legs = 4 print(Cat)
The way to access even the private value:
12345678910class Cat: def __init__(self, name = 'Kitty', age = 1): self.name = name self.age = age # Private self.__number_of_legs = 4 cat = Cat() # Access the private value print(cat._Cat__number_of_legs)
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Запитайте мені питання про цей предмет
Сумаризуйте цей розділ
Покажіть реальні приклади
Awesome!
Completion rate improved to 7.69
Private and Public Concepts
Свайпніть щоб показати меню
Encapsulation provides access to the methods and attributes of the class.
Private or public
Some attributes and/or methods cannot be accessed or modified. For example, it is correct not to change the number_of_legs
of your cat
object (usually, this value is 4).
This attribute must be private - not available outside the class.
By default, all methods and attributes are public in the Python class.
To make it private, add two __
before the variable name:
12345678class Cat: def __init__(self, name = 'Kitty', age = 1): self.name = name self.age = age # Private self.__number_of_legs = 4 print(Cat)
The way to access even the private value:
12345678910class Cat: def __init__(self, name = 'Kitty', age = 1): self.name = name self.age = age # Private self.__number_of_legs = 4 cat = Cat() # Access the private value print(cat._Cat__number_of_legs)
Дякуємо за ваш відгук!