笔记-python-动态添加属性

笔记-python-动态添加属性

 

1.      添加对象/类属性

添加对象属性

 

class Person(object):

    def __init__(self, newName, newAge):

        self.name = newName

        self.age = newAge

 

zhangsan = Person("张三", 18)

zhangsan.addr = "北京"    # 类对象zhangsan动态添加对象属性addr

print(zhangsan.name)    # 张三

print(zhangsan.age)     # 18

print(zhangsan.addr)    # 北京

 

lisi = Person("李四", 28)

print(lisi.name)        # 李四

print(lisi.age)         # 28

print(lisi.addr)        # 'Person' object has no attribute 'addr'

 

添加类属性:

class Person(object):

    def __init__(self, newName, newAge):

        self.name = newName

        self.age = newAge

 

Person.addr = "北京"  # 类Person动态添加类属性addr

 

zhangsan = Person("张三", 18)

print(zhangsan.name)    # 张三

print(zhangsan.age)     # 18

print(zhangsan.addr)    # 北京

 

lisi = Person("李四", 28)

print(lisi.name)    # 李四

print(lisi.age)     # 28

print(lisi.addr)    # 北京

 

2.      动态添加方法

类中有三种方法,实例,静态,类,其中静态和类方法没有什么太需要注意的。

def exp(s,*args):

    print('function exp.')

 

A = type('A',(),{'exp':exp})

 

a = A()

 

class B():

    def help1():

        pass

 

 

b = B()

 

@staticmethod

def exp2():

    print('function exp2.')

 

B.exp2 = exp2

 

 

@classmethod

def exp3(cls):

    print('function exp3.')

 

B.exp3 = exp3

 

结果输出:

>>> b

<__main__.B object at 0x0000003949041E80>

>>> b.exp2

<function exp2 at 0x0000003948702E18>

>>> b.exp3

<bound method exp3 of <class '__main__.B'>>

>>> a.exp

<bound method exp of <__main__.A object at 0x0000003949041400>>

>>> A.exp

<function exp at 0x00000039492B02F0>

>>> B.exp2

<function exp2 at 0x0000003948702E18>

>>> B.exp3

<bound method exp3 of <class '__main__.B'>>

>>> 

 

重点是添加实例方法

class B():

    def help1():

        pass

 

 

b = B()

 

@staticmethod

def exp2():

    print('function exp2.')

 

B.exp2 = exp2

 

 

@classmethod

def exp3(cls):

    print('function exp3.')

 

B.exp3 = exp3

 

 

def exp4():

    print('function exp4')

 

import types

 

B.exp = types.MethodType(exp,b)

B.exp4 = exp4

结果输出:

>>> b.exp

<bound method exp of <__main__.B object at 0x0000009F6FAF1EF0>>

>>> b.exp4

<bound method exp4 of <__main__.B object at 0x0000009F6FAF1EF0>>

>>> b.exp3

<bound method exp3 of <class '__main__.B'>>

>>> b.exp2

<function exp2 at 0x0000009F6D6A2E18>

>>> b.help1

<bound method B.help1 of <__main__.B object at 0x0000009F6FAF1EF0>>

实例方法,实例方法,类方法,静态方法,实例方法,注意其中的区别。

 

3.      __slots__

上面是如何添加属性,python也提供了一个特殊变量来限制实例可添加的属性名。

注意,是限制实例的属性名。

class C():

    __slots__ = ('name', 'age')

    pass

 

结果输出:

>>> c.ty = 45

Traceback (most recent call last):

  File "<pyshell#58>", line 1, in <module>

    c.ty = 45

AttributeError: 'C' object has no attribute 'ty'

 

4.      总结

python的一切都是类,除了参数传递需要注意外,其实各种方法对外部的接口都是差不多的。

 

posted @ 2019-03-18 15:07  木林森__𣛧  阅读(210)  评论(0)    收藏  举报