top | item 12880837

(no title)

bjw181 | 9 years ago

What is encapsulation in any language? Put simply, we encapsulate mainly to prevent mistakingly altering data. For example, private methods and variables.

    Class Foo:
        def __init__(self):
            self.__im_private()
    
        def bar(self):
            print('baz')

        def __im_private(self):
            print('back off, I can only be called by the class')

discuss

order

xcoding|9 years ago

Could you elaborate?

probinso|9 years ago

Encapsulation in object oriented programming is a term we use to describe joining of conceptual topics. A class generally models a conceptual topic, the data and methods on the class allow a clean interface to operations from that topic.

This extends the idea that 'the existence of a public method acts a documentation for what you can do with a object`. The existence of private methods and data are only to the benefit of the developer of the class.

Python's standards for encapsulation are a little different, because you cannot hide methods and data the same way you would with other languages. This is made apparent with public interfaces to private methods like in .__iter__(self): methods.