python中property魔法方法原理_Python类中的魔法方法之 __slots__原理解析
在類中每次實(shí)例化一個(gè)對(duì)象都會(huì)生產(chǎn)一個(gè)字典來保存一個(gè)對(duì)象的所有的實(shí)例屬性,這樣非常的有用處,可以使我們?nèi)我獾娜ピO(shè)置新的屬性。
每次實(shí)例化一個(gè)對(duì)象python都會(huì)分配一個(gè)固定大小內(nèi)存的字典來保存屬性,如果對(duì)象很多的情況下會(huì)浪費(fèi)內(nèi)存空間。
可通過__slots__方法告訴python不要使用字典,而且只給一個(gè)固定集合的屬性分配空間
class Foo(object):
__slots__ = ("x","y","z")
def __init__(self,x,y):
self.x = x
self.y = y
self.z = None
def tell_info(self,name):
return getattr(self,name)
c = Foo(10,20)
# 設(shè)置和獲取__slots__中設(shè)置的可訪問實(shí)例屬性
print(c.tell_info("x")) # 結(jié)果:10
c.z=50
print(c.tell_info("z")) # 結(jié)果:50
# 設(shè)置一個(gè)不在__slots__中存在的屬性,會(huì)報(bào)錯(cuò)
c.e = 70 # AttributeError: 'Foo' object has no attribute 'e'
# 訪問對(duì)象.__dict__ 也會(huì)直接報(bào)錯(cuò)
print(c.__dict__) # AttributeError: 'Foo' object has no attribute '__dict__'
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
本文標(biāo)題: Python類中的魔法方法之 __slots__原理解析
本文地址: http://www.cppcns.com/jiaoben/python/270081.html
總結(jié)
以上是生活随笔為你收集整理的python中property魔法方法原理_Python类中的魔法方法之 __slots__原理解析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue 引用网络css_vue如何引用其
- 下一篇: oracle ndv,CBO_ORACL