Ramy Ramy - 1 month ago 6x
Python Question

python empty class object

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:

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"


I'm wondering if there's a way to dynamically define a function for 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?


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)