问题
In python, what is the difference between protected and public variable in a class
class A:
def __init__(self):
self._protected="protected"
self.__private="private"
self.public="public"
>>> a = A()
>>> a.public
'public'
>>> a._protected
'protected'
>>>
Can someone please explain me the difference, and guide me on how to use protected variable in python [In case my method is usage is false]
Thanks in Advance.
回答1:
None of those terms except "public" really apply in Python.
The "private" version only "works" due to the mangling effect __
has on the name, but it's still possible to access it.
>>> a = A()
>>> print(a._A__private)
private
"Protected" here is even weaker "protection". It can be accessed normally as you show. It's only by convention that a single underscore prefix shouldn't be used. A single underscore prefix has some effect when wildcard importing, but I don't believe it has any effect when used in an attribute name.
Python does not have "private" class attributes. There may be some clever ways of emulating them, but they are hacks at best.
回答2:
Public members (generally methods declared in a class) are accessible from outside the class. The object of the same class is required to invoke a public method. This arrangement of private instance variables and public methods ensures the principle of data encapsulation.
Protected members of a class are accessible from within the class and are also available to its sub-classes. No other environment is permitted access to it. This enables specific resources of the parent class to be inherited by the child class.
Python doesn't have any mechanism that effectively restricts access to any instance variable or method. Python prescribes a convention of prefixing the name of the variable/method with single or double underscore to emulate the behaviour of protected and private access specifiers.
All members in a Python class are public by default. Any member can be accessed from outside the class environment.
Use protected in majority of the cases. Doesnt allows direct access of the variable.
来源:https://stackoverflow.com/questions/63455194/what-is-the-difference-between-protected-and-public-variable-in-python