Created
April 15, 2010 06:29
-
-
Save keturn/366764 to your computer and use it in GitHub Desktop.
method or function? why explicit self
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
extra credit, continued: