ZetCode

Python __get__ Method

Last modified November 17, 2026 Python 3.15

Descriptors are objects that define how an attribute is accessed. Their central hook, __get__, is called when the descriptor is found on a class or instance. The built-in property, plain functions, and classmethod are all built on this protocol. This article shows the arguments of __get__, then uses it to build a property, bind a method, cache a value, and check types.

The descriptor protocol

Python calls __get__(instance, owner) when a descriptor is accessed. instance is the object the attribute was read from, or None for a class-level access; owner is always the class that holds the descriptor. The hook returns the value that the access yields.

basic_get.py
class Logged:
    def __init__(self, value):
        self.value = value

    def __get__(self, instance, owner):
        where = "instance" if instance is not None else "class"
        print(f"get {self.value} via {where}, owner {owner.__name__}")
        return self.value


class Demo:
    attr = Logged(42)


obj = Demo()
print(obj.attr)
print(Demo.attr)

Reading obj.attr passes the instance, while reading Demo.attr passes None. Both calls receive Demo as the owner. The descriptor prints the first line of each pair, and the outer print supplies the returned value. Returning self when instance is None is the usual way to expose the descriptor itself on the class.

$ python basic_get.py
get 42 via instance, owner Demo
42
get 42 via class, owner Demo
42

Building a property

A property is a descriptor that calls a function to compute its value. The class below stores the getter and invokes it on instance access, reproducing the core of the built-in property.

property_descriptor.py
class MyProperty:
    def __init__(self, getter):
        self.getter = getter

    def __get__(self, instance, owner):
        print("descriptor __get__")
        if instance is None:
            return self
        return self.getter(instance)


class Circle:
    def __init__(self, radius):
        self.radius = radius

    @MyProperty
    def diameter(self):
        return self.radius * 2


circle = Circle(5)
print(circle.diameter)
print(type(Circle.diameter).__name__)

Reading circle.diameter calls __get__ and returns 10. Accessing Circle.diameter on the class also calls __get__, but with instance is None, so the descriptor returns itself; type(...) then reports MyProperty. That is why the hook is printed twice.

$ python property_descriptor.py
descriptor __get__
10
descriptor __get__
MyProperty

Method binding

Functions are descriptors too. When a function is stored on a class, its __get__ returns a bound object that supplies the instance as the first argument. The example reproduces that with functools.partial.

method_binding.py
from functools import partial


class Method:
    def __init__(self, func):
        self.func = func

    def __get__(self, instance, owner):
        if instance is None:
            return self
        return partial(self.func, instance)


class Greeter:
    def __init__(self, name):
        self.name = name

    @Method
    def greet(self):
        return f"Hello, {self.name}"


g = Greeter("Alice")
print(g.greet())
print(type(Greeter.greet).__name__)

Calling g.greet() reaches the bound partial and prints the greeting. Accessing Greeter.greet on the class returns the descriptor object itself, as the printed type name shows, so no instance is supplied in that case.

$ python method_binding.py
Hello, Alice
Method

Caching a computed value

A descriptor can store a computed result in the instance's own __dict__. The first access computes it and later accesses return the stored value. A name derived from the function avoids collisions.

cached_property.py
class Cached:
    def __init__(self, func):
        self.func = func
        self.cache_name = f"_cache_{func.__name__}"

    def __get__(self, instance, owner):
        if instance is None:
            return self
        if self.cache_name not in instance.__dict__:
            print("computing")
            instance.__dict__[self.cache_name] = self.func(instance)
        return instance.__dict__[self.cache_name]


class Data:
    def __init__(self, values):
        self.values = values

    @Cached
    def doubled(self):
        return [v * 2 for v in self.values]


d = Data([1, 2, 3])
print(d.doubled)
print(d.doubled)
print(d.__dict__)

The word “computing” appears only once even though the attribute is read twice. The final line shows the cache entry stored in the instance dictionary. Reading through instance.__dict__ rather than a normal attribute avoids triggering the descriptor again.

$ python cached_property.py
computing
[2, 4, 6]
[2, 4, 6]
{'values': [1, 2, 3], '_cache_doubled': [2, 4, 6]}

Type checking with a data descriptor

Adding __set__ makes a descriptor a data descriptor, which takes priority over the instance dictionary. The pair can enforce a rule on every assignment while storing the value under a plain name.

type_checking.py
class Typed:
    def __init__(self, name, expected):
        self.name = name
        self.expected = expected

    def __get__(self, instance, owner):
        if instance is None:
            return self
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, self.expected):
            raise TypeError(f"{self.name} must be {self.expected.__name__}")
        instance.__dict__[self.name] = value


class Person:
    name = Typed("name", str)
    age = Typed("age", int)

    def __init__(self, name, age):
        self.name = name
        self.age = age


p = Person("Alice", 30)
print(p.name, p.age)
try:
    p.age = "thirty"
except TypeError as e:
    print(type(e).__name__, e)

Valid values are stored and read back. Assigning a string to age raises TypeError from __set__. Because data descriptors are consulted before instance attributes, storing under instance.__dict__ is safe here and does not cause recursion.

$ python type_checking.py
Alice 30
TypeError age must be int

Best practices

Descriptors are powerful but easy to get wrong:

Source

object.__get__ - Python documentation

Descriptor HowTo - Python documentation

Descriptor invocation - Python documentation

In this article we have implemented the __get__ method. We have covered the descriptor protocol, properties, method binding, caching, and type checking. For related topics, see Python __getattr__ method, Python __set__ method, and Python __delete__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.