python基础之动态添加属性和方法

python是一门动态语言,即可以在运行的过程中修改代码。

一:即在代码运行过程中可以添加属性,方法(实例方法,静态方法,类方法)

示例代码:

 1 import types
 2 class Person:
 3     def __init__(self,newName,newAge):
 4         self.name = newName
 5         self.age = newAge
 6     def eat(self):
 7         print('-----%s正在吃东西-----'%self.name)
 8 #实例方法
 9 def run(self):
10     print('-------%s正在跑步------'%self.name)
11 p = Person('起哥',25)
12 p.addr='上海市浦东新区' #动态添加属性
13 print(p.addr)
14 p.eat()
15 p.run = types.MethodType(run,p) #动态添加实例方法,其中MethodType(run,p)中run是要添加到对象中的方法,p为要添加的对象
16 p.run()
17 
18 #静态方法
19 @staticmethod
20 def sleep():
21     print('-----静态方法-----')
22 #类方法
23 @classmethod
24 def drink(cls):
25     print('------类方法--------')
26 
27 Person.sleep = sleep #动态添加静态方法
28 Person.sleep()
29 Person.drink=drink #动态添加类方法
30 Person.drink()

运行结果:

1 上海市浦东新区
2 -----起哥正在吃东西-----
3 -------起哥正在跑步------
4 -----静态方法-----
5 ------类方法--------

二:__slots__

    因为Python是动态语言,有事我们需要限制实例属性的添加,这时就用到了__slots__ ,

为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的变量__slots__用来限制该class实例能添加的属性。

示例1:

1 class Person:
2     __slots__ = ('name','age')
3 p = Person()
4 p.name='qw'
5 p.age =13

运行结果:

Process finished with exit code 0

此时运行结果正常

示例2:

1 class Person:
2     __slots__ = ('name','age')
3 p = Person()
4 p.name='qw'
5 p.age =13
6 p.addr='上海'#这个addr属性不是上面规定的属性之内,所以报错

运行结果:

1 Traceback (most recent call last):
2   File "E:/pychemDevlop/pritices/property.py", line 67, in <module>
3     p.addr='上海'
4 AttributeError: 'Person' object has no attribute 'addr'
5 
6 Process finished with exit code 1
原文地址:https://www.cnblogs.com/qigege1104/p/8627441.html