美文网首页
Python动态绑定属性方法

Python动态绑定属性方法

作者: 继即鲫迹极寂寂 | 来源:发表于2019-01-17 13:16 被阅读0次

python是动态语言,可以为实例动态绑定属性、方法,也可以为类动态绑定方法。即在用到的时候定义。为实例动态绑定的属性、方法,其它实例不可用。类绑定的方法,所有类实例都可以用。

class Animal(object):
    def __init__(self, name, num):
        self.name = name
        self.num = num

    def printNum(self):
        print("%s有%s个" % (self.name, self.num))
d = Animal("哈士奇", 88)

动态给实例绑定属性

d.width = 90 
print(d.width) ----------> 90

动态给实例绑定方法

def setLength(self, length):
    self.length = length
from types import MethodType
d.setLength = MethodType(setLength, d)
d.setLength(99)
print(d.length) ----------> 99

动态给类绑定方法

def setColor(self, color):
    self.color = color
Animal.setColor = setColor
d.setColor("black")
print(d.color) ----------> black

slots

可以限制类实例绑定属性,实例只能绑定slots指定的属性

class Animal(object):
    __slots__ = ("name", "num")

d = Animal()
d.name = "哈士奇"
print(d.name)
d.color = "black" #因为__slots__没有包括"color"属性,所以不可用
print(d.color)
image.png
slots对子类不起作用。但如果子类也定义了slots,则子类的实例属性是子类和父类的slots共同限制的。
class Cat(Animal):
    pass
c = Cat()
c.color = "white"
print(c.color)
        
class Dog(Animal):
    __slots__ = ("legth", "width")
dog = Dog()
dog.color = "yellow"
print(dog.color)
image.png

相关文章

  • 使用__slots__实现动态绑定

    Python作为动态语言,可以实现动态绑定属性和实例方法等。 动态绑定属性 动态绑定实例方法 给一个实例绑定的方法...

  • Python动态绑定属性方法

    python是动态语言,可以为实例动态绑定属性、方法,也可以为类动态绑定方法。即在用到的时候定义。为实例动态绑定的...

  • 实例属性和类属性

    实例属性和类属性: 由于Python是动态语言,根据类创建的实例可以任意绑定属性。 (1)给实例绑定属性的方法是通...

  • python __slots__ 限制属性

    Python 是动态语言,允许我们动态的增加属性和方法 同样也有办法限制属性的动态绑定 如上所示可以规定 clas...

  • Python:面向对象编程(进阶)

    类动态绑定方法与限定实例属性 类动态绑定方法 前面我们说了如何给类动态的添加属性,那么如何动态绑定方法呢?如下示例...

  • python-实例属性与类属性

    由于Python是动态语言,根据类创建的实例可以任意绑定属性。 给实例绑定属性的方法是通过实例变量,或者通过sel...

  • 27. OOP-实例属性和类属性

    由于Python是动态语言,根据类创建的实例可以任意绑定属性。给实例绑定属性的方法是通过实例变量,或者通过self...

  • 第31节:实例属性和类属性

    由于Python是动态语言,根据类创建的实例可以任意绑定属性。 给实例绑定属性的方法是通过实例变量,或者通过sel...

  • Python学习笔记09-面向对象高级编程

    __slots__属性 在python中class被实例化后仍然可以绑定新属性和方法,这就是动态语言的特性。 注意...

  • Python学习之路(面向对象之使用__slots__)

    面向对象高级编程之slots python 是 动态语言 因此我们可以动态的给实例绑定属性和方法 小结 使用slo...

网友评论

      本文标题:Python动态绑定属性方法

      本文链接:https://www.haomeiwen.com/subject/nfubdqtx.html