[Python 学习笔记] 9: Class
2009-10-13 00:00:00 来源:WEB开发网2. 添加方法
>>> class Class1:
pass
>>> def test():
print "test"
>>> def hello(self):
print "hello ", id(self)
>>> a = Class1()
>>> dir(a)
['__doc__', '__module__']
>>> Class1.test = test
>>> dir(a)
['__doc__', '__module__', 'test']
>>> b = Class1()
>>> dir(b)
['__doc__', '__module__', 'test']
>>> a.hello = hello
>>> a.hello(a)
hello 13860416
>>> dir(a)
['__doc__', '__module__', 'hello', 'test']
>>> dir(b)
['__doc__', '__module__', 'test']
3. 改变现有方法
>>> class Class1:
def test(self):
print "a"
>>> def test(self):
print "b"
>>> Class1.test = test
>>> Class1().test()
b
另外,有几个内建函数方便我们在运行期进行操作。
>>> hasattr(a, "x")
False
>>> a.x = 10
>>> getattr(a, "x")
10
>>> setattr(a, "x", 1234)
>>> a.x
1234
Python Open Class 是如何实现的呢?我们看一下下面的代码。
>>> class Class1:
pass
>>> a = Class1()
>>> a.__dict__
{}
>>> a.x = 123
>>> a.__dict__
{'x': 123}
>>> a.x
123
>>> a.test = lambda i: i + 1
>>> a.test(1)
2
>>> a.__dict__
{'test': <function <lambda> at 0x00D39DB0>, 'x': 123}
更多精彩
赞助商链接