I'm teaching a python class on Object Oriented Programming and as I'm brushing up on how to explain Classes, I saw an empty class definition:
class Employee:
pass
the example then goes on to define a name and other attributes for an object of this class:
john = Employee()
john.full_name = "john doe"
interesting!
I'm wondering if there's a way to dynamically define a function for an instance of a class like this? something like:
john.greet() = print 'hello world!'
this doesn't work in my python interpreter but is there another way of doing it?
You could use AttrDict
Install attrdict from PyPI:
It's useful in other situations too - like when you need attribute access to dict keys.
Try with
lambda
:The you'll be able to do:
EDIT: Thanks Thomas K for the note - this works on
Python 3.2
and not for Python2, whereprint
appeared to bestatement
. But this will work forlambda
s, without statements (right? Sorry, I know onlypython3.2
(: )A class is more or less a fancy wrapper for a
dict
of attributes to objects. When you instantiate a class you can assign to its attributes, and those will be stored infoo.__dict__
; likewise, you can look infoo.__dict__
for any attributes you have already written.This means you can do some neat dynamic things like:
as well as assigning to a particular instance. (EDIT: added
self
parameter)You could also use "named tuples" from the
collection
standard module. Named tuples work like "ordinary" tuples but the elements have names and you can access the elements using the "dot syntax". From the collection docs: