Skip to content

Instantly share code, notes, and snippets.

@keturn
Created April 15, 2010 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keturn/366764 to your computer and use it in GitHub Desktop.
Save keturn/366764 to your computer and use it in GitHub Desktop.
method or function? why explicit self
class A(object):
# method
def foo(self, x):
print self, x
# function -- defined after A is closed.
def bar(self, y):
print self, y
A.bar = bar
a = A()
print "class:", A
print "A.foo:", A.foo
print "bar:", bar
print "A.bar:", A.bar
print "a.foo:", a.foo
print "a.bar:", a.bar
a.foo("alpha")
a.bar("bravo")
bar("octopus", "bacon")
#
# extra credit:
#
# it doesn't exactly work that way in reverse:
foo = A.foo
print foo
try:
foo("llama", "hummus")
except TypeError, err:
print err
# but you can do it:
foo = A.foo.im_func
print foo
foo("marmot", "tahini")
@keturn
Copy link
Author

keturn commented Apr 15, 2010

extra credit, continued:

assert not (a.foo is A.foo)
assert A.foo.im_func is a.foo.im_func

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment