Python 类机制
>>> class MyData(object): //类作为名称空间容器
... pass
...
>>> mathObj = MyData()
>>> mathObj.x=4
>>> mathObj.y=5
>>> mathObj.x+mathObj.y
9
>>>
>>> mathObj.x*mathObj.y
20
self(实例对象)参数自动由解释器传递
类中方法只能通过实例来调用
类中静态变量可以直接使用
实例仅拥有数据属性
在类属性可变的情况下
>>> class Foo(object):
... x = {2003:'poe2'}
...
>>> foo = Foo()
>>> foo.x
{2003: 'poe2'}
>>> foo.x[2004] = 'valid path'
>>> foo.x
{2003: 'poe2', 2004: 'valid path'}
>>> Foo.x
{2003: 'poe2', 2004: 'valid path'}
>>> del foo.x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object attribute 'x' is read-only
绑定方法与非绑定方法
非绑定方法:主要场景是在派生一个子类,而且要覆盖父类的方法,需要调用这个父类中想要覆盖的构造方法
http://blog.sina.com.cn/s/blog_3fe961ae0100kew0.html
http://cowboy.1988.blog.163.com/blog/static/75105798201091141521583/
>>> class TestMethod:
... def func():
... print "hehe"
...
>>> test_method = TestMethod()
>>> test_method.func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes no arguments (1 given)
>>> class TestStaticMethod:
... def foo():
... print 'calling static method foo()'
... foo = staticmethod(foo)
...
>>> class TestClassMethod:
... def foo(cls):
... print 'calling class method foo()'
... print 'foo() is part of class:',cls.__name__
... foo = classmethod(foo)
...
>>>
>>>
>>>
>>> Test_foo = TestStaticMethod()
>>> Test_foo.foo()
calling static method foo()