Object Oriented

Visibility

Python

 

Visibility

Python 2.7
class Person:
  
  def __init__(self, name, fingerprint):
    self.name = name
    self._fingerprint = fingerprint
    
  def __debug():
    pass

Python doesn't support Access Modifiers like other Programming Languages like Java.

It is a convention to use single or double underscores to mark properties and methods as not-for-public-use.

 

Public

Python 2.7
class Person:
  
  def __init__(self, name):
    self.name = name
  
  def greet(self):
    print("Hi! I'm " + name);

Anything that is defined in a class can be accessed publicly.

There is a small exception for names that have double underscores at the beginning of them which will be explained in Private Card.

 

Private

Python 2.7
class Person:
  
  def __init__(self, id):
    __person_id = id
    
  def debug(self):
    print("__person_id: " + str(self.__person_id))

Python mangles properties and methods names start start with double underscores (__).

By mangling these names, these properties and methods cannot be accessed directly by their names.

Still, by looking into the __dict__ property of an object, you can see and access these properties and methods.

person1 = Person(123)

id = person1.__person_id    # Error