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 ...
随机推荐
- Navicat 创建 Mysql 函数
1.点击新建函数 2.写函数,保存为v1 3.调用 SELECT id,v1(id) from 表
- mysql表大小写问题
查看大小写区分 mysql> show variables like "%case%"; linux在mysql安装完后默认:区分表名的大小写,不区分列名的大小写 改变表名的 ...
- MySQL Server has gone away报错原因汇总分析(转自:http://cenalulu.github.io/mysql/mysql-has-gone-away/)
原因1. MySQL 服务宕了 判断是否属于这个原因的方法很简单,执行以下命令,查看mysql的运行时长 $ mysql -uroot -p -e "show global status l ...
- 并查集hdu4424
Conquer a New Region Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Oth ...
- 分布式锁的实现(java)
当对接第三方接口时,往往会碰到同一时间发送了大量相同的请求,这个时候或许就是第三方发送接口的失误了.而我们需要做的就是针对这个情况来强化我们的系统.这个时候就需要用到分布式锁.让这些请求只有一个能发送 ...
- LightOj 1422 Halloween Costumes(区间DP)
B - Halloween Costumes Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu Submit ...
- nginx 下使用 bootstrap 字体的问题
使用boostrap时,出现 glyphicons-halflings-regular.ttf glyphicons-halflings-regular.woff glyphicons-halflin ...
- php安装xmlwriter遇到报错及解决方法
Q1:make的时候报' error: 'zend_class_entry' has no member named 'default_properties''错误, A:把 错误行C文件中defau ...
- fork(2) - Linux man page
fork(2): create child process - Linux man page https://linux.die.net/man/2/fork fork(2) - Linux man ...
- Ubuntu proxychains && setProxy及 unsetProxy
https://www.socks-proxy.net/ (ubuntu proxy )[ lantern -addr 0.0.0.0:8787 proxychains4 printenv http: ...