3 回答

TA贡献1111条经验 获得超0个赞
method_one
a_test.method_one()
Test.method_one(a_test)
method_two
TypeError
>>> a_test = Test() >>> a_test.method_two()Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: method_two() takes no arguments (1 given)
class Test(object): def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method two"
type
method_two
.
>>> a_test = Test()>>> a_test.method_one()Called method_one>>> a_test.method_two()Called method_two>>> Test.method_two()Called method_two

TA贡献1847条经验 获得超7个赞
class C(object): def foo(self): pass
>>> C.foo<unbound method C.foo>>>> C.__dict__['foo']<function foo at 0x17d05b0>
foo
__getattribute__
C.foo
>>> C.__dict__['foo'].__get__(None, C)<unbound method C.foo>
__get__
None
>>> c = C()>>> C.__dict__['foo'].__get__(c, C)<bound method C.foo of <__main__.C object at 0x17bd4d0>>
staticmethod
class C(object): @staticmethod def foo(): pass
staticmethod
__get__
>>> C.__dict__['foo'].__get__(None, C)<function foo at 0x17d0c30>

TA贡献1943条经验 获得超7个赞
>>> class Class(object):
... def __init__(self):
... self.i = 0
... def instance_method(self):
... self.i += 1
... print self.i
... c = 0
... @classmethod
... def class_method(cls):
... cls.c += 1
... print cls.c
... @staticmethod
... def static_method(s):
... s += 1
... print s
...
>>> a = Class()
>>> a.class_method()
1
>>> Class.class_method() # The class shares this value across instances
2
>>> a.instance_method()
1
>>> Class.instance_method() # The class cannot use an instance method
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead)
>>> Class.instance_method(a)
2
>>> b = 0
>>> a.static_method(b)
1
>>> a.static_method(a.c) # Static method does not have direct access to
>>> # class or instance properties.
3
>>> Class.c # a.c above was passed by value and not by reference.
2
>>> a.c
2
>>> a.c = 5 # The connection between the instance
>>> Class.c # and its class is weak as seen here.
2
>>> Class.class_method()
3
>>> a.c
5
添加回答
举报