当前位置:网站首页>(9) Attribute introspection
(9) Attribute introspection
2022-07-26 02:52:00 【It's hard to recover】
( One ) Private property
Definition : The variables defined in a class are called class attributes , Then there are two kinds of class attributes , Public attribute and private attribute respectively .
Private property definition :
- Single underscore start :_attr It can be accessed directly from the outside
- Start with double underscore :__attr Not directly accessible from the outside , Was renamed , So you can't access it from outside , Changed to _Test_attr2
class Test(object):
_attr = 100 # It can be accessed directly from the outside
__attr2 = 200 # Not directly accessible from the outside , Was renamed , So you can't access it from outside , Changed to _Test_attr2
t = Test()
# View all the properties and methods of this class
print(Test.__dict__)
# Print the results
{'__module__': '__main__', '_attr': 100, '_Test__attr2': 200, '__dict__': <attribute '__dict__' of 'Test' objects>, '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None}
Be careful : python There is no real privatization support , But you can get pseudo private by underlining , There is one most python The code follows the habit : Underlined , The name of the prefix should be treated as private API Part of ( Whether it's a function 、 Methods are also data members ). It should be seen as an implementation detail , If there is any change , Without notice .
( Two )__dict__
- Class call __dict__ attribute , Return a dictionary ( Class properties and methods )
- The instance __dict__ attribute , Return the instance properties related to the instance
class MyTest:
name = 100
age = 99
def __init__(self, a, b):
self.a = a
self.b = b
m = MyTest(1, 2)
print(m.__dict__) # If it is the object , Then it is to get the instance attribute of the object
print(MyTest.__dict__) # Get the properties and methods of the class
ddd = dir(m) # 1、 All you get is the name of the attribute , No value . 2、 Get all the properties that can be used in the parent class .
print(ddd)
Some children's shoes mentioned dir What is this built-in function for , He followed __dict__ The difference is that :
- __dict What is obtained is that the attribute and the corresponding value are generated in the form of key value pairs , Printed out is a dictionary ,dir This built-in function only gets the name of the attribute .
- dir Built in functions treat objects as long as they are methods that can be used ( Including the parent class ) All the methods in are printed out .
( 3、 ... and ) Built in properties __slots__
effect 1: Limit the properties that an object can set
By default , Class has a dictionary for storing properties . This wastes space for objects with few instance variables . When creating a large number of instances , Space consumption may become acute .
You can define __slots__ To override the default __dict__ Behavior .__slots__ The declaration accepts a sequence of instance variables , And only enough space is reserved for each variable value in each instance . Because you didn't create... For each instance __dict__, So save space .
So let's create one list Object of type , Let's see if we can set li Of name attribute =999, Through the printing results, it is found that , Why? ? Why do I create a class and I can set the properties of the object of this class at will ?
li = list()
li.name = 999
print(li)
# Print the results
AttributeError: 'list' object has no attribute 'name'
class MyTest:
pass
m = MyTest()
m.name = 'wangBigxia'
print(m.__dict__)
# Print the results
{'name': 'wangBigxia'}At that time, we are MyTest Add a in this class __slots__ = [] Give it a try , Found our settings m.name Will report a mistake ,m.__dict__ He will make a mistake , Why? ? This is it. __slot_ The role of : Limit the properties that an object can set .
Because of the settings __slots__ = [] , The set is an empty list , No attribute of this object can be added .

Let's modify the code :__slots__ = ['name'] Give it a try :
name Properties can be set , however age Property cannot be set . Because of me __slots__ = ['name']

In class __init__ When initializing attributes for an instantiated object of a class , If __slots__ Set his attribute range , that init Methods are not allowed to set or initialize other properties .
Practical tips : When your class will instantiate a lot , Can pass __slots__ Stop this __dict__ The creation of .
as everyone knows , Every time you instantiate an object , Will be generated automatically __dict__ Method . When your class will instantiate a lot , This method can save memory overhead .
( Four ) Custom attribute access
You can define the following methods to define the meaning of attribute access of class instances ( visit 、 Assign or delete x.name)
- object.__getattr__ Called when the property search does not find the property in the usual place
- object.__getattribute__ When looking for properties , The method will be called the first time
- object.__setattr__ When setting properties , Call this method to set properties
- ojbect.__delattr stay del obj.attr Trigger when deleting a property
1、 get attribute
I created a Demo class , I instantiate an object at this time , Then call him. name When attributes , Wrong report , Because he didn't name Attribute, right .

At this time, we re create a class , Then call again and try
It can be seen from the print results , What he printed was none, Why didn't you make a mistake ? Because when you use objects .name When looking for attributes , In fact, what is called at the first time is __getattribute__ Method .

Because we have no code to find attributes , So he printed out None, But how can we let him implement the code that finds attributes by himself ? We can actually call the parent class __getattribute__ Method .
When we execute t.name When , First, call __getattribute__ Method , Because this method calls the method of the parent class to find the element , then t Objects have no name attribute , Will throw an exception , When the attribute is not found , Trigger AttributeError When exception occurs, it will call __getattr__ Method

Then we are __getattribute__ Method except for calling the parent class __getattribute__ Out of the way , What else to do , We need to save the results we find And back to , Code up .

2、 Set properties

3、 Delete attribute
It is the same as setting attribute query attribute , I won't go into that .
( 5、 ... and ) A case of custom attribute management mechanism
Demo1 : Define a MyClass class : Can be initialized name,age Two attributes
name Property can only be set to str
age Property can only be set to int
name Property cannot be deleted
age If the output of the search result is less than 0, return 0
"""
Define a MyClass class : Can be initialized name,age Two attributes
name Property can only be set to str
age Property can only be set to int
name Property cannot be deleted
age If the output of the search result is less than 0, return 0
"""
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
def __setattr__(self, key, value):
if key == 'name':
if isinstance(value, str):
super().__setattr__(key, value)
else:
raise TypeError('name Property can only be set to string ')
elif key == 'age':
if isinstance(value, int):
super().__setattr__(key, value)
else:
raise TypeError('age Property can only be set to int')
else:
super().__setattr__(key, value)
m = MyClass('musen', 18)
print(m.name, m.age)
( 6、 ... and ) Magic method of sequence type data index value
Let's write a class by ourselves , Why can't we pass through objects [ Property name ] Get his attribute value , It's because our handwritten class doesn't implement __getitem__ This method .

Let's modify the code and try :

Now upload the source code , You can try it yourself :
class MyClass(object):
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def __getitem__(self, item):
print('Item:', item)
return getattr(self, item)
def __setitem__(self, key, value):
setattr(self, key, value)
def __delitem__(self, key):
print(" Delete index :", key)
delattr(self, key)
def __len__(self):
"""len(obj)"""
return len(self.__dict__)
# return 999
m = MyClass(11, 22, 33, 44)
# print(m['d'])
#
# m['abc'] = 11111
#
# print(m['abc'])
#
# del m['b']
# res = len(m)
# print(res)
边栏推荐
- 栈题目:文件的最长绝对路径
- Overview of pytoch's API
- 朋友刚学完自动化测试就拿25Koffer,我功能测试何时才能到头?
- [纯理论] YOLO v4: Optimal Speed and Accuracy of Object Detection
- 规范自己debug的流程
- C language -- program environment and preprocessing
- Self-supervised learning method to solve the inverse problem of Fokker-Planck Equation
- Longest Substring Without Repeating Characters
- How to design automated test cases?
- Zhimeng prompts you how to solve the problem of setting the field as linkage type
猜你喜欢

(pc+wap) dream weaving template vegetable and fruit websites

HLS Experiment 1 -- multiplier

Exclusive interview with ringcentral he Bicang: empowering future mixed office with innovative MVP

EAM系统能帮助企业做什么?

JS get the time composition array of two time periods

Stack Title: the longest absolute path of a file

Effectively solve the problem of garbled code when idea runs the web project (with detailed steps)
![[pure theory] Yolo v4: optimal speed and accuracy of object detection](/img/1f/f38c3b38feed9e831ad84b4bbf81c0.png)
[pure theory] Yolo v4: optimal speed and accuracy of object detection

测试/开发程序员老了怎么办?挥之不去残酷的事实......

Self-supervised learning method to solve the inverse problem of Fokker-Planck Equation
随机推荐
Case: using kept+haproxy to build a Web Cluster
Autojs cloud control source code + display
Image recognition (VII) | what is the pooling layer? What's the effect?
(pc+wap) dream weaving template vegetable and fruit websites
Effectively solve the problem of garbled code when idea runs the web project (with detailed steps)
Annotation development management third-party beans
GAMES101复习:着色(Shading)、渲染管线
eslint常见报错集合
从各大APP年度报告看用户画像——标签,比你更懂你自己
JS get the time composition array of two time periods
织梦提示你设定了字段为联动类型如何解决
Information System Project Manager - Chapter 10 communication management and stakeholder management examination questions over the years
墨天轮高分技术文档分享——数据库安全篇(共48个)
Skill list of image processing experts
移位距离和假设的应用
From the annual reports of major apps, we can see that user portraits - labels know you better than you do
Have you ever seen this kind of dynamic programming -- the stock problem of state machine dynamic programming (Part 1)
MySQL教程:MySQL数据库学习宝典(从入门到精通)
[纯理论] YOLO v4: Optimal Speed and Accuracy of Object Detection
Eslint common error reporting set