开发者

What is the proper term for the methods defined inside of a Python class before the class is instantiated?

Using this example from http://docs.python.org/tutorial/classes.html#class-objects:

class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'

According to those docs, f is an attribute reference that returns a function object.

Is there any shorter way of saying what f is? Can I call it a method of a class (note how I didn't say "class method" which is incorrect)? Or a function defined within a class? Or an instance method?

In开发者_如何学Go other words, what's the formal short-hand term for f in terms of its relation to MyClass?


If you're referring specifically to the f returned by MyClass.f, then f is an unbound method of MyClass. Or at least that's what the REPL calls it:

>>> MyClass.f
<unbound method MyClass.f>

In general though, I don't think anyone would fault you for simply calling it a "method", plain and simple. Or, in terms of its relation to MyClass, a method of MyClass.


I'd say it's an instance method(or member function), because this method is only accessible when you bind it with an instance, instance.f() or MyClass.f(instance).


x = MyClass()
def __init__(self):
    self.data = []
print x.i
print x.f()
print MyClass.__doc__

# Instance x = MyClass()
# More __init__(self) is important
# Sorry my english. I'm from Brazl 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜