python动态绑定属性和方法
基于Python 2.7.13测试。
Python是动态语言,在类定义了之后,还可以动态地绑定属性和方法。
下面先来看怎么给类的实例动态地绑定属性和方法。
>>> class Student(object):
... pass
...
>>> stu1 = Student();
>>> stu1.name = 'Tom'
>>> print(stu1.name)
Tom
>>> print(dir(stu1))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'name']
>>>
>>> def set_age(self, age):
... self.age = age
...
>>> set_age(stu1, 20)
>>> print(stu1.age)
20
>>> print(dir(stu1))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'age', 'name']
>>> #并没有绑定方法到实例上
...
>>> from types import MethodType
>>> stu1.set_age = MethodType(set_age, stu1)
>>> stu1.set_age(33)
>>> print(stu1.age)
33
>>> print(dir(stu1))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'age', 'name', 'set_age']
>>> #绑定的属性和方法只属于stu1的,对于其他实例不起作用
...
>>> stu2 = Student()
>>> print(dir(stu2))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__']
看怎么给类动态地绑定属性和方法。
>>> class Student(object):
... pass
...
>>> def set_name(self, name):
... self.name = name
...
>>> from types import MethodType
>>> Student.set_name = MethodType(set_name, Student)
>>> print(dir(Student))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'set_name']
>>> stu1 = Student()
>>> stu1.set_name('Rose')
>>> stu2 = Student()
>>> stu2.set_name('Jack')
>>> print(stu1.name)
Jack
>>> print(stu2.name)
Jack
>>> ########
>>> class Student(object):
... pass
...
>>> def set_name(self, name):
... self.name = name
...
>>> Student.set_name = set_name
>>> print(dir(Student))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'set_name']
>>> stu1 = Student()
>>> stu1.set_name('Rose')
>>> stu2 = Student()
>>> stu2.set_name('Jack')
>>> print(stu1.name)
Rose
>>> print(stu2.name)
Jack
想要限制实例属性,只允许对Student实例添加name和age属性。__slots__变量,来限制该class实例能添加的属性。
>>> class Student(object):
... __slots__ = ('name', 'age')
...
>>> stu1 = Student()
>>> stu1.name = 'John'
>>> stu1.addr = 'Beijing'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'addr'
__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用。
>>> class MidStudent(Student):
... pass
...
>>> stu2 = MidStudent()
>>> stu2.addr = 'Beijing'
>>> print(stu2.addr)
Beijing
slots只能限制添加属性,不能限制通过添加方法来添加属性。
>>> from types import MethodType
>>>
>>> class School(object):
... __slots__ = ('name')
...
>>> def set_city(self, city):
... self.city = city
...
>>> School.set_city = MethodType(set_city, School)
>>>
>>> sch = School()
>>> sch.set_city('BeiJing')
>>> print(sch.city)
BeiJing
Python创建class的方法就是使用type()函数。 type()函数既可以返回一个对象的类型,又可以创建出新的类型。
>>> def fun(self, name='World'):
... print('Hello %s' % name)
...
>>> #创建Hello类
... Hello = type('Hello', (object,), dict(hello=fun))
>>>
>>> h = Hello()
>>> h.hello()
Hello World
要创建一个class对象,type()函数依次传入3个参数:
- class的名称。
- 继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法。
- class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。
通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。
python动态绑定属性和方法的更多相关文章
- python 类属性与方法
Python 类属性与方法 标签(空格分隔): Python Python的访问限制 Python支持面向对象,其对属性的权限控制通过属性名来实现,如果一个属性有双下划线开头(__),该属性就无法被外 ...
- Python 给实例或者类动态绑定属性和方法
首页定义一个class,创建一个实例之后,我们可以给该实例绑定任何属性和方法,先定义class: class Student: def __init__(self, name, score): sel ...
- Python动态绑定属性slots的使用
当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性.废话不多说,我们看一个例子: class Person(object): pass ...
- Python——特殊属性与方法
Python 对象 中以双下划线开头和结尾的属性称为特殊属性,由于对象的方法也属于属性,因此以双下划线开头和结尾的方法称为特殊方法.对这些对象执行一些特定的运算时,Python会自动视图调用这些实例的 ...
- Python 类属性和方法
import types class Dog(object): __slots__ = ("name", "color", "info") ...
- 菜鸟初识python request属性及方法说明
if request.REQUEST.has_key('键值'): HttpRequest对象的属性 参考: 表 H-1. HttpRequest对象的属性 属性 描述 path 表示提交请求页面完 ...
- python request属性及方法说明
if request.REQUEST.has_key('键值'): HttpRequest对象的属性 参考: 表 H-1. HttpRequest对象的属性 属 性 描述 path 表示提 ...
- 转:python request属性及方法说明
转:http://blog.csdn.net/u013398398/article/details/52214582 if request.REQUEST.has_key('键值'): HttpRe ...
- Python复数属性和方法操作实例
转自: https://blog.csdn.net/henni_719/article/details/56665254 #coding=utf8 ''' 复数是由一个实数和一个虚数组合构成,表示为: ...
随机推荐
- MyBatis-Plus使用教程
单机版 安装环境 上传压缩包到/usr/local/software/下 解压安装包,进入解压目录的bin目录下,启动命令: ./solr start -force 默认端口是8983,请求虚拟机, ...
- 高斯消元 o(n^3) 取摸和不取摸
#include<bits/stdc++.h> using namespace std; ; int a[MAXN][MAXN];//增广矩阵 int x[MAXN];//解集 bool ...
- SQL相关语句
1.分类 数据定义语言(DDL),用来定义数据库.表 列 ,用到的关键字:create.alter.drop. 数据操作语言(DML),数据库进行更行的操作, insert.delete.update ...
- terraform 几个方便的工具
几个方便的terraform 工具,方便了解terraform terraform-docs 方便的查看资源的信息(支持markdown,json 格式),对于ci/cd 很方便 项目地址 https ...
- Explicit
Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor ...
- oracle之 安装oracle指定jdk 或者如何解决提示框显示不全
在centos7下,安装oracle 11g. gnome的桌面.各个参数配置好后,运行runInstaller命令.此时弹出安装界面,在一次次点击[下一步]的时候,中间会弹出对话框,可是对话框显示不 ...
- 使用 Travis 进行持续集成
廖雪峰教程:https://www.liaoxuefeng.com/article/0014631488240837e3633d3d180476cb684ba7c10fda6f6000
- 菜鸟如何使用hanlp做分词的过程记录
菜鸟如何使用hanlp做分词的过程记录 最近在学习hanlp的内容,准备在节后看看有没有时间整理一波hanlp分享下,应该还是会像之前分享DKHadoop一样的方式吧.把整个学习的过程中截图在配文字的 ...
- JDK1.8中如何用ScriptEngine动态执行JS
JDK1.8中如何用ScriptEngine动态执行JS jdk1.6开始就提供了动态脚本语言诸如JavaScript动态的支持.这无疑是一个很好的功能,毕竟Java的语法不是适合成为动态语言.而JD ...
- Device Identifier and Device DNA初识
Device Identifier and Device DNA初识 信息来源 怎么样去用这个DNA: