python基础拾遗007--python语言的动态特性

python语言的动态性主要体现在:

     **可是给实例添加属性

     **可以给实例添加方法

    **可以给类添加属性

     **可以给类添加类方法或者静态方法

先定义一个简单的测试类

class Person(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
        print("name:" + name + " age:" + str(age))

1.给实例添加属性

p1 = Person('小红',100)
p1.phone = '178212122121'#给对象添加属性
print(p1.phone)

2.给实例添加方法

#动态添加方法给对象
def info(self):
    print('---this is out from info function----')
    print('name:'+self.name.upper() + '######')
    print('---end of info function----')

#通过types.MethodType(funcName,instance)将info方法动态的添加给对象p1
import types
p1.info = types.MethodType(info,p1)
p1.info()
#注意,这样也是正确可执行的
newName = types.MethodType(info,p1)
newName()

3.给类添加属性

Person.country='china' #给类添加属性
p2=Person('小明',99)
print(p2.country)
#print(p2.phone) #这一行会报错,因为phone属性只添加给了对象p1。
                #p2.country 不会报错,是以为country属性添加给了类Person,所有Person类的实例共享。

4.给类添加静态方法和类方法

#给类添加静态方法
@staticmethod
def staticFunc(name):
    print('我是一个静态方法:'+name)

Person.staticF=staticFunc
Person.staticF("hello")

#给类添加类方法
@classmethod
def funcMethod(cls,test):
    print('我是一个类方法:' + test)
Person.funcM = funcMethod
Person.funcM("HAHA")

5.__slots__限制给对象添加属性的范围,但是不限制给类添加属性。

class Person(object):
    __slots__=('name','phone')
    def __init__(self):
        print('--Person--init---')

p1 = Person()
p1.name='haha'
p1.phone='1782123213'
Person.country='china' #给类添加__slots__之外的属性是可以的
print('----'+p1.country+'****')
print('---分割线--')
p1.age=12 #这一行会报错,'Person' object has no attribute 'age'
Person.country='china'

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值