68

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?

2
  • 1
    Possible? Yes. A good idea? Rarely (outside of some metaprogramming, of course). Commented Jun 1, 2011 at 16:43
  • 4
    The shortest empty class definition I've seen is from gossamer-threads.com/lists/python/python/832915#832915: Employee=type('Employee',(),{}) and then john=Employee() etc. Commented Jun 3, 2015 at 9:18

4 Answers 4

55

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 in foo.__dict__; likewise, you can look in foo.__dict__ for any attributes you have already written.

This means you can do some neat dynamic things like:

class Employee: pass
def foo(self): pass
Employee.foo = foo

as well as assigning to a particular instance. (EDIT: added self parameter)

Sign up to request clarification or add additional context in comments.

Comments

21

Try with lambda:

john.greet = lambda : print( 'hello world!' )

The you'll be able to do:

john.greet()

EDIT: Thanks Thomas K for the note - this works on Python 3.2 and not for Python2, where print appeared to be statement. But this will work for lambdas, without statements (right? Sorry, I know only python3.2 (: )

6 Comments

This doesn't actually work: lambdas can't contain statements.
@katrielalex - Works perfect on my python 3.2 (with added parentheses for print, of course). What statemets?
@Kirii: In Python 2, print is a statement. You're adding brackets because in Python 3, it became a function.
@Thomas K - ah, thanks! I didn't know, that print is statement in Python2.
Since the OP wanted to dynamically define a function, perhaps the print example wasn't the best. +1
|
2

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:

>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)

Comments

-1

You could use AttrDict

>>> from attrdict import AttrDict
>>> my_object = AttrDict()
>>> my_object.my_attribute = 'blah'
>>> print my_object.my_attribute
blah
>>> 

Install attrdict from PyPI:

pip install attrdict 

It's useful in other situations too - like when you need attribute access to dict keys.

1 Comment

sure, more dependencies for the God of Dependencies

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.