python 动态添加属性及方法及“__slots__的作用”

1.动态添加属性

class Person(object):
    def __init__(self, newName, newAge):
        self.name = newName
        self.age = newAge


laowang = Person("老王", 10000)
print(laowang.name)
print(laowang.age)
laowang.addr = "北京...."
print(laowang.addr)


laozhao = Person("老赵", 18)
#print(laozhao.addr)

Person.num = 100
print(laowang.num)
print(laozhao.num)

2.动态添加方法

#!/usr/local/bin/python3
# -*- coding:utf-8 -*-

import types 
class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age


def eat(self):
    print('---%s正在吃----' %self.name)

p1 = Person('p1',100)
#p1.eat = eat             #右边的eat指向eat 函数内存地址,赋值给p1对象的eat属性
#p1.eat()                 #这样调用会报错

########那样怎么添加呢????
##在开头导入模块types,再用如下方法:
p1.eat = types.MethodType(eat,p1)
p1.eat()

#####用法#################

>>> import types
>>> help(types.MethodType)
Help on class method in module builtins:


class method(object)
| method(function, instance)

 

python 动态添加属性及方法及“__slots__的作用”

##############__slots__ 的作用################

In [18]: class Person(object):
    ...:     __slots__ = ("name","age")       #####只能添加元祖中定义了的属性,不在元组内的不行
    ...:     

In [19]: p1 = Person()

In [20]: p1.name = 'haha'

In [21]: p1.addr = 'beijing'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-be5d7a142f3a> in <module>()
----> 1 p1.addr = 'beijing'

AttributeError: 'Person' object has no attribute 'addr'