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 ...
随机推荐
- 【Android M】获取屏幕锁定的相关信息:“无”,“滑动”,“PIN码”,"图案","密码"
ENV: Android M 6.0.1 import android.os.UserHandle; import com.android.internal.widget.LockPa ...
- WEB安全番外第六篇--关于通过记录渗透工具的Payload来总结和学习测试用例
背景: 在WEB安全的学习过程中,了解过了原理之后,就是学习各种Payload,这里面蕴藏着丰富的知识含量,是在基本上覆盖了漏洞原理之后的进一步深入学习的必经之路.无理是Burpsuite还是Sqlm ...
- @font-face 字体
一.@font-face是CSS3中的一个模块,把自己定义的Web字体嵌入到你网页中 @font-face的语法规则 @font-face { font-family: <YourWebFont ...
- 【BZOJ3003】LED BFS+状压DP
[BZOJ3003]LED Description LED屏是由一个庞大的点阵小灯泡组成的,一开始每个小灯泡都不发光.每一行一共有N个小灯泡,依次标号为1~n.现在给定K个点,要求这K个点发光,其余点 ...
- WCF(一) 创建第一个WCF
定义服务契约-创建宿主程序-创建客户端程序访问服务 namespace HelloService { /// <summary> /// 服务契约 /// </summary> ...
- 无向连通图求割点(tarjan算法去掉改割点剩下的联通分量数目)
poj2117 Electricity Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 3603 Accepted: 12 ...
- Linux系统下JDK安装配置(转载)
转载出处:http://www.cnblogs.com/xuliangxing/p/7066913.html 本文主要介绍的是如何是Linux环境下安装JDK的,因为Linux环境下,很多时候也离不开 ...
- Animate CC 2017
一.Animate CC 2017 下载及安装 http://www.ddooo.com/softdown/86853.htm
- poj3974 Palindrome【回文】【Hash】【二分】
Palindrome Time Limit: 15000MS Memory Limit: 65536K Total Submissions: 13157 Accepted: 5028 Desc ...
- 转!idea启动后发现tomcat前面出现红色或是灰色的问号
原博文地址:https://blog.csdn.net/z_zhy/article/details/83068168 直接在idea里 点击File------settings,在搜索框直接搜tomc ...