Python学习札记(三十六) 面向对象编程 Object Oriented Program 7 __slots__
参考:slots
NOTE
1.动态语言灵活绑定属性及方法。
#!/usr/bin/env python3
class MyClass(object):
def __init__(self):
pass
def func(obj):
print(obj.name, obj.age)
def main():
h = MyClass()
h.name = 'Chen'
h.age = '20'
func(h)
if __name__ == '__main__':
main()
给对象h绑定了属性name和age。
sh-3.2# ./oop7.py
Chen 20
绑定一个新的方法:
from types import MethodType
def f(self):
print('I\'m new here!')
h.f = MethodType(f, h) # new method
h.f()
I'm new here!
但是这种绑定的方法并不存在于新建的对象:
h1 = MyClass()
h1.f()
Traceback (most recent call last):
File "./oop7.py", line 28, in <module>
main()
File "./oop7.py", line 25, in main
h1.f()
AttributeError: 'MyClass' object has no attribute 'f'
给类绑定一个方法,解决这个问题:
MyClass.f = f
h1 = MyClass()
h1.f()
I'm new here!
通常情况下,上面的f方法可以直接定义在class中,但动态绑定允许我们在程序运行的过程中动态给class加上功能,这在静态语言中很难实现。
2.__slots__
但是,如果我们想要限制实例的属性怎么办?比如,只允许对MyClass实例添加name和age属性。
为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性:
#!/usr/bin/env python3
class MyClass(object):
"""docstring for MyClass"""
__slots__ = ('name', 'age')
def __init__(self):
super(MyClass, self).__init__()
pass
def main():
h = MyClass()
h.name = 'Chen'
h.age = 20
h.city = 'FuZhou'
if __name__ == '__main__':
main()
sh-3.2# ./oop8.py
Traceback (most recent call last):
File "./oop8.py", line 17, in <module>
main()
File "./oop8.py", line 14, in main
h.city = 'FuZhou'
AttributeError: 'MyClass' object has no attribute 'city'
__slots__用tuple定义允许绑定的属性名称,由于'city'没有被放到__slots__中,所以不能绑定city属性。
使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
#!/usr/bin/env python3
class MyClass(object):
"""docstring for MyClass"""
__slots__ = ('name', 'age')
def __init__(self):
super(MyClass, self).__init__()
pass
class Student(MyClass):
"""docstring for Student"""
def __init__(self):
super(Student, self).__init__()
pass
def main():
h = MyClass()
h.name = 'Chen'
h.age = 20
# h.city = 'FuZhou'
h1 = Student()
h1.name = 'Chen'
h1.age = 20
h1.city = 'FuZhou'
print(h1.name, h1.age, h1.city)
if __name__ == '__main__':
main()
sh-3.2# ./oop8.py
Chen 20 FuZhou
2017/3/2
Python学习札记(三十六) 面向对象编程 Object Oriented Program 7 __slots__的更多相关文章
- Python学习札记(三十四) 面向对象编程 Object Oriented Program 5
参考:获取对象信息 NOTE 1.type()函数可以用来判断对象的类型: >>> type(123) <class 'int'> >>> type(' ...
- Python学习札记(三十九) 面向对象编程 Object Oriented Program 10
参考:使用枚举类 NOTE #!/usr/bin/env python3 from enum import Enum def main(): Mouth = Enum('Mouth', ('Jan', ...
- Python学习札记(三十八) 面向对象编程 Object Oriented Program 9
参考:多重继承 NOTE #!/usr/bin/env python3 class Animal(object): def __init__(self, name): self.name = name ...
- Python学习札记(三十五) 面向对象编程 Object Oriented Program 6
参考:实例属性和类属性 NOTE Python是动态语言,根据类创建的实例可以任意绑定属性. class Student(object): def __init__(self, name): self ...
- Python学习札记(三十二) 面向对象编程 Object Oriented Program 3
参考:访问限制 NOTE 1.eg. #!/usr/bin/env python3 class Student(object): """docstring for Stu ...
- Python学习札记(二十六) 函数式编程7 修饰器
修饰器 NOTE 1.函数对象有一个__name__属性,可以拿到函数的名字: #!/usr/bin/env python3 def now(): print('2017/2/19') def mai ...
- Python学习札记(三十) 面向对象编程 Object Oriented Program 1
参考:OOP NOTE 1.面向对象编程--Object Oriented Programming,简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数. ...
- Python学习札记(四十) 面向对象编程 Object Oriented Program 11
参考:使用元类 NOTE: type() 1.type()函数可以用于检查一个类或者变量的类型. #!/usr/bin/env python3 class Myclass(object): " ...
- Python学习札记(三十七) 面向对象编程 Object Oriented Program 8 @property
参考:@property NOTE 1.在绑定参数时,为了避免对属性不符合逻辑的操作,需要对传入的参数进行审核. #!/usr/bin/env python3 class MyClass(object ...
随机推荐
- struts2的核心和工作原理 <转>
在学习struts2之前,首先我们要明白使用struts2的目的是什么?它能给我们带来什么样的好处? 设计目标 Struts设计的第一目标就是使MVC模式应用于web程序设计.在这儿MVC模式的好处就 ...
- 不同linux下两网卡绑定方法
记得原来在做性能测试时,为了提高网络吞吐率.必须将两个网卡绑定一起工作.绑定方法如下: 一.CentOS 配置 1.编辑虚拟网络接口配置文件,指定网卡IP: # vi /etc/sysconfig ...
- Windows下Git免密码pull&push
Windows下Git在使用http方式的时候clone,pull,push需要输入用户名及密码,通过以下设置可以免密码 在用户文件夹创建文件.git-credentials内容如下 https:// ...
- CodeForces 17D Notepad(同余定理)
D. Notepad time limit per test 2 seconds memory limit per test 64 megabytes input standard input out ...
- FZU 2098 刻苦的小芳(卡特兰数,动态规划)
Problem 2098 刻苦的小芳 Accept: 42 Submit: 70 Time Limit: 1000 mSec Memory Limit : 32768 KB Problem Descr ...
- 南京网络赛B-The writing on the wall
30.43% 2000ms 262144K Feeling hungry, a cute hamster decides to order some take-away food (like frie ...
- Online handwriting recognition using multi convolution neural networks
w可以考虑从计算机的“机械性.重复性”特征去设计“低效的”算法. https://www.codeproject.com/articles/523074/webcontrols/ Online han ...
- Qt 模拟鼠标点击(QApplication::sendEvent(ui->pushbutton, &event0);)
QPoint pos(0,0);QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt ...
- 原!上线遇到的问题, java序列化关键字transient 修饰的属性变成null了
1.问题描述: 某个功能点,user对象 放入session,后再另外地方取出,结果某个字段没有了.再本地和测试环境都是ok的,但是线上环境就是不行. 后来看到这个user对象的那个属性是加了tran ...
- Python开发【Tornado】:简介与使用
Tornado框架 简介: Tornado是使用Python编写的一个强大的.可扩展的Web服务器.它在处理严峻的网络流量时表现得足够强健,但却在创建和编写时有着足够的轻量级,并能够被用在大量的应用和 ...