Fabrice Pombet於 2013年8月31日星期六UTC+8上午1時43分28秒寫道: > On Saturday, August 17, 2013 2:26:32 PM UTC+2, Fernando Saldanha wrote: > > > I am new to Python, with experience in Java, C++ and R. > > > > > > > > > > > > As I understand encapsulation is not a big thing in the Python world. I > > read that you can put two underscores before the name of a variable within > > a class declaration but in the many examples of code I looked at this is > > not widely used. I also read that encapsulation is "unpythonic." > > > > > > > > > > > > Questions: > > > > > > > > > 2) If it is in fact true that encapsulation is rarely used, how do I deal > > with the fact that other programmers can easily alter the values of members > > of my classes? > > > > > Fernando, it is widely accepted that Python pays very little attention to > encapsulation as a principle set in stone. Chaz's definition of encapsulation > is also mine. Now you need to consider that taking this principle off the > hostel of OOP does not mean that you can do whatever you fancy and you can't > make anything unsettable. > > > > There are plenty of techniques within Python that allow you to protect your > arguments (in particular, decorators) inside a Class. > > > > Now, lets get to the pretentious philosophical discussion: I guess > encapsulation is quite the opposite of, say, dynamic typing, which is > arguably core in Python. In practice this allows Python to be less verbose: > at the end of the day, if you look back at your previous languages, don't you > find that some of their compulsory features are usually more of a pain than > something useful in practice? And after all, whither encapsulation? Can't we > just have objects whose arguments are determined externally if we want to? > > And that is the ballgame: as my old tutor says: "the claptrap of setters and > getters does not need to be here if it is unnecessary". I would add: "so long > as you can have them when you deem it necessary", and Python allows that.
The way to perform encapsulation in Python can be achieved by writing methods in C to be compiled as an extension which can be used by all instances of some classes in the upper level. CYTHON is easy to be used for the job. -- http://mail.python.org/mailman/listinfo/python-list