当前位置:网站首页>Data and Introspection__ dict__ Attributes and__ slots__ attribute
Data and Introspection__ dict__ Attributes and__ slots__ attribute
2022-07-06 02:51:00 【chuntian_ tester】
Variables defined in a class are called class attributes , Methods defined in a class are called class methods ; Class attribute classification :
1. Public attribute : General attribute
2. Private property : With “_” or "__" The first attribute is called a private attribute , Private properties can also be inherited and accessed .
for example :
class Info(object):
_name = ' Springfield '
__age = 4
if __name__ == '__main__':
i = Info()
print(i._name) # Output : Springfield
print(Info._name) # Output : Springfield
print(Info._Info__age) # Output :4
print(i.__age) # Output :AttributeError: 'Info' object has no attribute '__age'
print(Info.__age) # Output :AttributeError: 'Info' object has no attribute '__age'
_name attribute : Outside through “Info._name" or “ object ._name" visit .
__age attribute : External access only “Info._Info__age" visit .
3.__dict__ Method :
3.1 Class calls the class itself __dict__ attribute , What is returned is the dictionary of the properties and methods of a class .
3.2 The instance object calls the... Of the object itself __dict__ attribute , What is returned is a dictionary of the properties and methods of an instance object .
class Info(object):
_name = ' Springfield '
__age = 4
def run(self):
print('run')
if __name__ == '__main__':
i = Info()
i.gender = 'male'
# Call the object's __dict__ Method :{'gender': 'male'}
print(i.__dict__)
# The calling class __dict__ Method :
# {'__module__': '__main__', '_name': ' Springfield ', '_Info__age': 4,
# 'run': <function Info.run at 0x7f84a00a0d30>,
# '__dict__': <attribute '__dict__' of 'Info' objects>,
# '__weakref__': <attribute '__weakref__' of 'Info' objects>, '__doc__': None}
print(Info.__dict__)
It can be seen that : When the class is created ,Python Will automatically add {'__dict__': <attribute '__dict__' of 'Info' objects>, '__weakref__': <attribute '__weakref__' of 'Info' objects>, '__doc__': None} These attributes , But we don't need these attributes , If this class is instantiated with many objects , Then a lot of memory space will be wasted to store these attributes we don't need , Increased performance overhead . How to solve ?
Through built-in properties :__slots__ To limit the properties that a class can be defined , Solve the problem that the class is automatically added with attributes .
__slots__ attribute :slots Properties cannot be inherited
1. Specify the properties that class objects can bind ;
2. Limiting attributes ;
3. To save memory : Defined __slots__ After attribute , Then the object will not be generated automatically __dict__ attribute .
By defining... In a class __slots__ Property to override the default __dict__ Behavior ;__slots__ Declare to receive a sequence of instance variables , And only enough space is reserved for each variable value in each instance , Therefore, it will not be created for each instance __dict__, So save space .
class Test(object):
# adopt __slots__ Restrict the attributes that a class can exist ,slots Properties cannot be inherited
__slots__ = ['name', 'age']
def __init__(self, name, age, gender):
self.name = name
self.age = age
# self.gender = gender # __slots__ This is not included in gender attribute , So there's an error
class Case(object):
# The test platform creates test cases
__slots__ = ['case_id', "title", "url", "data", "expected"]
def __init__(self):
self.case_id = None
self.title = None
self.url = None
self.data = None
self.expected = None
if __name__ == '__main__':
t = Test(' Springfield ', "4", 'male')
# View the of the class __dict__ Method , The properties and methods of the discovery class are no longer in __dict__ Content. .
print(Test.__dict__) # {'__module__': '__main__', '__slots__': ['name', 'age'], '__init__': <function Test.__init__ at 0x7f81200a0d30>, 'age': <member 'age' of 'Test' objects>, 'name': <member 'name' of 'Test' objects>, '__doc__': None}
print(t.__dict__) # AttributeError: 'Test' object has no attribute '__dict__'
print(t.age)
print(t.name)
print(t.gender)
# Output :AttributeError: 'Test' object has no attribute 'gender'
边栏推荐
- Redis cluster deployment based on redis5
- Elimination games
- 会员积分营销系统操作的时候怎样提升消费者的积极性?
- 如何精准识别主数据?
- My C language learning records (blue bridge) -- files and file input and output
- 【若依(ruoyi)】ztree 自定义图标(iconSkin 属性)
- 【Unity3D】GUI控件
- Fault analysis | analysis of an example of MySQL running out of host memory
- 2345文件粉碎,文件强力删除工具无捆绑纯净提取版
- Sign SSL certificate as Ca
猜你喜欢

Microsoft speech synthesis assistant v1.3 text to speech tool, real speech AI generator
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 13](/img/29/49da279efed22706545929157788f0.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 13

Déduisez la question d'aujourd'hui - 729. Mon emploi du temps I

MySQL advanced notes

PMP每日一练 | 考试不迷路-7.5

RobotFramework入门(一)简要介绍及使用

微服务注册与发现

Misc (eternal night), the preliminary competition of the innovation practice competition of the National College Students' information security competition
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24](/img/2e/b1f348ee6abaef24b439944acf36d8.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 24

建模规范:命名规范
随机推荐
Single instance mode of encapsulating PDO with PHP in spare time
How to improve the enthusiasm of consumers when the member points marketing system is operated?
华为、H3C、思科命令对比,思维导图形式从基础、交换、路由三大方向介绍【转自微信公众号网络技术联盟站】
[Yu Yue education] basic reference materials of digital electronic technology of Xi'an University of Technology
CSP numeric sort
Déduisez la question d'aujourd'hui - 729. Mon emploi du temps I
codeforces每日5題(均1700)-第六天
Introduction to robotframework (I) brief introduction and use
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 14
MySQL winter vacation self-study 2022 11 (8)
The difference between sizeof and strlen in C language
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 7
2020.02.11
PMP practice once a day | don't get lost in the exam -7.5
米家、涂鸦、Hilink、智汀等生态哪家强?5大主流智能品牌分析
Apt installation ZABBIX
Redis skip table
Qt发布exe软件及修改exe应用程序图标
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23
C语言sizeof和strlen的区别