Skip to Content
Python 3 Object-Oriented Programming - Third Edition
book

Python 3 Object-Oriented Programming - Third Edition

by Dusty Phillips
October 2018
Beginner to intermediate
466 pages
12h 2m
English
Packt Publishing
Content preview from Python 3 Object-Oriented Programming - Third Edition

Using functions as attributes

One of the interesting effects of functions being objects is that they can be set as callable attributes on other objects. It is possible to add or change a function to an instantiated object, demonstrated as follows:

class A: 
    def print(self): 
        print("my class is A") 
 
def fake_print(): 
    print("my class is not A") 
 
a = A() 
a.print() 
a.print = fake_print 
a.print() 

This code creates a very simple class with a print method that doesn't tell us anything we didn't know. Then, we create a new function that tells us something we don't believe.

When we call print on an instance of the A class, it behaves as expected. If we then set the print method to point at a new function, it tells us something different:

my class is ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python 3 Object-Oriented Programming - Second Edition

Python 3 Object-Oriented Programming - Second Edition

Dusty Phillips

Publisher Resources

ISBN: 9781789615852Supplemental Content