Skip to content
All Posts

Notes on Python Functions and Classes

Experiments with Python functions and classes involving binding, equality, method lookup, callability, and name mangling.

Bound and unbound methods

In Python 2, accessing a method through an instance returns a bound method carrying that instance, while accessing it through the class returns an unbound method that expects an instance explicitly. Python 3 simplified this behavior: class access returns the underlying function, and instance access still creates a bound method through the descriptor protocol.

Equality

is tests object identity; == calls equality logic such as __eq__. Use identity for singletons such as None and equality for values. A custom equality implementation should normally be consistent with hashing when instances are hashable.

Discovering methods and callable attributes

dir, the class dictionary, and the inspect module expose different views of members. callable(value) tells whether an attribute can be called, but it does not imply that the value is a method defined directly on that class.

Hidden attributes

Names beginning with two underscores are name-mangled to include the class name. This prevents accidental collisions in subclasses; it is not an access-control boundary. A single leading underscore remains the conventional signal that an attribute is internal.


Originally published on SegmentFault.