Should you use attribute references in Python? [closed]
Allowing 'Attribute references ' is against Encapsulation/Data Hiding. In development we sholud avoid using it. right ?
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
MyClass.i=98765
"Data hiding" is simply one aspect of OOP, not part of the definition of it. And "encapsulation" is a separate concept.
Python most certainly is not pure OOP. For one, it doesn't enforce data hiding. Also, users of objects can add attributes on the fly. Also, there are several APIs in the libraries that use a functional programming paradigm. Plus, there are the lambda functions (which are really cool, by the way).
Whatever a "pure OOP language" means, Python probably isn't it.
As for directly accessing attributes, it's actually encouraged in Python for simple classes, instead of writing explicit getters and setters. Read this article for more information.
Yes. Python trusts the developer to make his own choice about this. Whereas you can forbid access to a property in Java and C#, in Python the developer should know that he should not access a property of another class.
You can prefix a property with two underscores to make it harder to access. See name mangling.
There's nothing wrong with the original code you posted, but depending on the context there are alternatives you might consider.
You can use a property decorator like so:
class Pie(object):
_flavour = None
@property
def flavour(self):
return self._flavour
@flavour.setter
def flavour(self, value):
self._flavour = value
p = Pie()
p.flavour = 'cherry'
p.flavour
>>> 'cherry'
This is effectively a getter/setter, but without requiring users of your class to use methods like p.get_flavour()
. It also has advantages over letting a user directly access the data, since you can add logic in the getters and setters (eg. caching a value in the getter).
If you have data that you don't want users of your class to access, you can prefix it with an underscore or double underscore, eg. _flavour
. Users can still access it by calling pie._flavour
, but the underscore signals your intent that it shouldn't be used in that way. See Private Variables and Methods in Python for a discussion on this.
精彩评论