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?
In Python, to write an empty class pass statement is used. pass is a special statement in Python that does nothing. It only works as a dummy statement. However, objects of an empty class can also be created.
To delete an object in Python, we use the 'del' keyword. A when we try to refer to a deleted object, it raises NameError.
The size of an empty class is not zero. It is 1 byte generally.
In Python, you don't declare variables as having any type. You just assign to them. A single variable can be assigned objects of different types in succession, if you wanted to do so.
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)
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 lambda
s, without statements (right? Sorry, I know only python3.2
(: )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With