Managing data access: private attributes

Object-Oriented Programming in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

All class data is public

we are all adults here

Object-Oriented Programming in Python

Restricting access

  • Naming conventions
  • Use @property to customize access
  • Overriding __getattr__() and __setattr__()
Object-Oriented Programming in Python

Naming convention: internal attributes

obj._att_name, obj._method_name()

  • Starts with a single _ → "internal"
  • Not a part of the public API
  • As a class user: "don't touch this"
  • As a class developer: use for implementation details, helper functions..

df._is_mixed_type , datetime._ymd2ord()

Object-Oriented Programming in Python

Naming convention: pseudoprivate attributes

obj.__attr_name , obj.__method_name()

  • Starts but doesn't end with __ → "private"
  • Not inherited
  • Name mangling: obj.__attr_name is interpreted as obj._MyClass__attr_name
  • Used to prevent name clashes in inherited classes

 

Leading and trailing __ are only used for built-in Python methods (__init__(),__repr__())!

Object-Oriented Programming in Python

Let's practice!

Object-Oriented Programming in Python

Preparing Video For Download...