avatar

magic methods

Examples for function built-in method

method explanation
_doc_ The function’s documentation string, or Noneif unavailable; not inherited by subclasses Writable
_name_ The function’s name Writable
_qualname_ The function’s qualified nameNew in version 3.3. Writable
_module_ The name of the module the function was defined in, or None if unavailable. Writable
_defaults_ A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value Writable
_code_ The code object representing the compiled function body. Writable
_globals_ A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined. Read-only
_dict_ The namespace supporting arbitrary function attributes. Writable
_closure_ None or a tuple of cells that contain bindings for the function’s free variables. See below for information on the cell_contents attribute. Read-only
python
1
2
3
4
def myfunction(arg1 = 1):
""" My function example"""
# test string
test = 'test_string'
python
1
myfunction.__doc__
' My function example'
python
1
myfunction.__name__
'myfunction'
python
1
myfunction.__qualname__
'myfunction'
python
1
myfunction.__module__
'__main__'
python
1
myfunction.__defaults__
(1,)
python
1
myfunction.__code__
<code object myfunction at 0x0000020E0443AB70, file "<ipython-input-1-d45fff7bc581>", line 1>
python
1
myfunction.__dict__
{}
python
1
myfunction.__closure__

Examples for class built-in method

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class MyClass(object):
''' My class example'''
def __init__ (self):
self.a = 0
self.b = 'test'
def __new__(cls):
print('Creating new instance')
return super(MyClass, cls).__new__(MyClass)
def __del__(self):
print('Deleting instance')
def __str__(self):
return 'Ass hole class'
def __getattr__(self, attr):
print('No such attribute!')
raise AttributeError
def __setattr__(self, attr, value):
self.__dict__[attr] = 1

Class methods:

python
1
dir(MyClass)
['__class__',
 '__del__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattr__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']
python
1
MyClass.__class__
type
python
1
MyClass.__bases__
(object,)
python
1
MyClass.__dict__
mappingproxy({'__module__': '__main__',
              '__doc__': ' My class example',
              '__init__': <function __main__.MyClass.__init__(self)>,
              '__new__': <staticmethod at 0x20e045c0be0>,
              '__del__': <function __main__.MyClass.__del__(self)>,
              '__str__': <function __main__.MyClass.__str__(self)>,
              '__getattr__': <function __main__.MyClass.__getattr__(self, attr)>,
              '__setattr__': <function __main__.MyClass.__setattr__(self, attr, value)>,
              '__dict__': <attribute '__dict__' of 'MyClass' objects>,
              '__weakref__': <attribute '__weakref__' of 'MyClass' objects>})

Instance methods:

python
1
test_instance = MyClass()
Creating new instance
python
1
dir(test_instance)
['__class__',
 '__del__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattr__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'a',
 'b']
python
1
test_instance.__dict__
{'a': 1, 'b': 1}
python
1
test_instance.__doc__
' My class example'
python
1
test_instance.__init__.__code__
<code object __init__ at 0x0000020E044FD8A0, file "<ipython-input-31-5e1debc8af67>", line 3>
python
1
test_instance.__setattr__.__doc__

Note: _del_() is NOT directly called when deleting instance. It has to be called eplicitely!

python
1
test_instance.__del__()
Deleting instance
python
1
print(test_instance)
Ass hole class
python
1
test_instance.__str__()
'Ass hole class'

The correspondence between operator symbols and method names is as follows:

Code
1
2
3
4
5
6
x<y calls x.__lt__(y),
x<=y calls x.__le__(y),
x==y calls x.__eq__(y),
x!=y calls x.__ne__(y),
x>y calls x.__gt__(y),
and x>=y calls x.__ge__(y).

python
1
2
3
4
5
6
object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)

_getattr_(self, attr) only gets called when attribute is not found

python
1
test_instance.d
No such attribute!



---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-45-4c7135cdd908> in <module>
----> 1 test_instance.d


<ipython-input-31-5e1debc8af67> in __getattr__(self, attr)
     13     def __getattr__(self, attr):
     14         print('No such attribute!')
---> 15         raise AttributeError
     16     def __setattr__(self, attr, value):
     17         self.__dict__[attr] = 1


AttributeError: 
python
1
test_instance.a
1

_setattr_ will do things when setting a value.

python
1
test_instance.d = 4
python
1
test_instance.d
1

评论