Does Python have “private” variables in classes?

后端 未结 12 1840
不思量自难忘°
不思量自难忘° 2020-11-21 23:06

I\'m coming from the Java world and reading Bruce Eckels\' Python 3 Patterns, Recipes and Idioms.

While reading about classes, it goes on to say that in Py

相关标签:
12条回答
  • 2020-11-21 23:43

    There is a variation of private variables in the underscore convention.

    In [5]: class Test(object):
       ...:     def __private_method(self):
       ...:         return "Boo"
       ...:     def public_method(self):
       ...:         return self.__private_method()
       ...:     
    
    In [6]: x = Test()
    
    In [7]: x.public_method()
    Out[7]: 'Boo'
    
    In [8]: x.__private_method()
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-8-fa17ce05d8bc> in <module>()
    ----> 1 x.__private_method()
    
    AttributeError: 'Test' object has no attribute '__private_method'
    

    There are some subtle differences, but for the sake of programming pattern ideological purity, its good enough.

    There are examples out there of @private decorators that more closely implement the concept, but YMMV. Arguably one could also write a class defintion that uses meta

    0 讨论(0)
  • 2020-11-21 23:44

    Python has limited support for private identifiers, through a feature that automatically prepends the class name to any identifiers starting with two underscores. This is transparent to the programmer, for the most part, but the net effect is that any variables named this way can be used as private variables.

    See here for more on that.

    In general, Python's implementation of object orientation is a bit primitive compared to other languages. But I enjoy this, actually. It's a very conceptually simple implementation and fits well with the dynamic style of the language.

    0 讨论(0)
  • 2020-11-21 23:47

    As mentioned earlier, you can indicate that a variable or method is private by prefixing it with an underscore. If you don't feel like this is enough, you can always use the property decorator. Here's an example:

    class Foo:
    
        def __init__(self, bar):
            self._bar = bar
    
        @property
        def bar(self):
            """Getter for '_bar'."""
            return self._bar
    

    This way, someone or something that references bar is actually referencing the return value of the bar function rather than the variable itself, and therefore it can be accessed but not changed. However, if someone really wanted to, they could simply use _bar and assign a new value to it. There is no surefire way to prevent someone from accessing variables and methods that you wish to hide, as has been said repeatedly. However, using property is the clearest message you can send that a variable is not to be edited. property can also be used for more complex getter/setter/deleter access paths, as explained here: https://docs.python.org/3/library/functions.html#property

    0 讨论(0)
  • 2020-11-21 23:47

    About sources (to change the access rights and thus bypass language encapsulation like java or C ++): You don't always have the sources and EVEN if you do, the sources are managed by a system that only allows certain programmers to access a source (in a professional context). Often, every programmer is responsible for certain classes and therefore knows what he can and cannot do. The source manager also locks the sources being modified and of course, manages the access rights of programmers.

    So i trust more in software than in human, by experience. So convention is good but MULTIPLE protections are better, like access management (real private variable) + sources management.

    0 讨论(0)
  • 2020-11-21 23:53

    "In java, we have been taught about public/private/protected variables"

    "Why is that not required in python?"

    For the same reason, it's not required in Java.

    You're free to use -- or not use private and protected.

    As a Python and Java programmer, I've found that private and protected are very, very important design concepts. But as a practical matter, in tens of thousands of lines of Java and Python, I've never actually used private or protected.

    Why not?

    Here's my question "protected from whom?"

    Other programmers on my team? They have the source. What does protected mean when they can change it?

    Other programmers on other teams? They work for the same company. They can -- with a phone call -- get the source.

    Clients? It's work-for-hire programming (generally). The clients (generally) own the code.

    So, who -- precisely -- am I protecting it from?

    0 讨论(0)
  • 2020-11-21 23:55

    It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you really want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.

    If you want to emulate private variables for some reason, you can always use the __ prefix from PEP 8. Python mangles the names of variables like __foo so that they're not easily visible to code outside the class that contains them (although you can get around it if you're determined enough, just like you can get around Java's protections if you work at it).

    By the same convention, the _ prefix means stay away even if you're not technically prevented from doing so. You don't play around with another class's variables that look like __foo or _bar.

    0 讨论(0)
提交回复
热议问题