python中的__slots__
生活随笔
收集整理的這篇文章主要介紹了
python中的__slots__
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為了達到限制的?的,Python允許在定義class的時候,定義一個特殊的 __slots__變量,來限制該class實例能添加的屬性:
class Foo(object):
??? __slots__ = ("a", "b")
??? # 限制動態使用對象名添加東西(屬性、方法)的名字
?
obj = Foo()
obj.a = 100
?
# print(obj.a)
?
def say_a(self):
??? print(self.a)
?
# Foo.c =say_a
?
import types
?
fun =types.MethodType(say_a, obj)
obj.c =fun
obj.c =200
print(obj.c)
?
注意:使用__slots__要注意,__slots__定義的屬性僅對當前類實例起作用,對于繼承的自類是不起作用的
總結
以上是生活随笔為你收集整理的python中的__slots__的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python常见错误及基本技巧
- 下一篇: python 经典100例 (61-80