Shallowly discuss the special methods of s 0en class s s 1en__ and s 2en__
- 2020-05-19 05:03:28
- OfStack
For a slightly convoluted example, step tracing with the PyScripter debugger lets you see the details of the image structure.
Change the original by 1, using the ready-made model of s 5en__ in the undefined subobject property.
## encoding:utf-8
"""
This class inherits object, object is Python The smallest unit can be in Python the ">>>" The console with dir(objct) or dir (__builtins__.object) The command looks at its properties, as you can see __setattr__, __new__... They are python You can have properties that any object in the dir(1) and dir(int) Check it out. You can see more. Here, 1 As a 1 Two instantiated int Object appears. And these __xxx__ What are properties good for? In the following code, we'll see __getitem__ and __setitem__ What's the use of ( These two properties are dict Very important in the object )
"""
class WPUnit(object):
def __init__(self):
self._res={}
def __setitem__(self,key,val):
self._res[key]=val
def __getitem__(self,key):
if self._res.has_key(key):
return self._res[key]
else:
r=WPUnit()
self.__setitem__(key,r)
return r
a=WPUnit()
a['a']['b']['c']['d']['e']['f']['g']=5
print a['a']['b']['c']['d']['e']['f']['g']
>>> class testsetandget:
kk = {};
def __getitem__(self, key):
return self.kk[key];
def __setitem__(self, key, value):
self.kk[key] = value;
>>> a = testsetandget()
>>> a['first'] = 1
>>> a['first']
1
>>> a.__setitem__('second', 2)
>>> a.__getitem__('second')
2
>>> a['second']
2
>>>