Skip to content

Instantly share code, notes, and snippets.

@mittenchops
Last active December 16, 2015 08:39
Show Gist options
  • Save mittenchops/5407811 to your computer and use it in GitHub Desktop.
Save mittenchops/5407811 to your computer and use it in GitHub Desktop.
Make a class from the command line and show quirks of inheritance after instantiation
>>> from __future__ import print_function
>>> class People: pass
>>>
>>> Fred = People()
>>> Fred.has_pants = True
# Now I'd like to create a method that says "I have pants" if Fred has pants. I make the function:
>>> f = lambda self: print("I have pants") if self.has_pants else None
# Now try to assign it to the class:
>>> setattr(People,"talk_about_pants",f)
>>> Fred.talk_about_pants()
I have pants
>>> f = lambda self,y: print("I have %s" % y)
>>> setattr(People,"say_this",f)
>>> Fred.say_this("rock and roll")
I have rock and roll
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment