Alex Rivera | Logout

Empty class object in Python

Asked 2011-06-01T15:50:56.147
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?

Edit
Report

1 Answer

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 (: )

answered 2011-06-01T15:52:15.190

Your Answer