Python day 9 (3) custom class, pythonday
1: __str _ (return user-friendly output)
1 >>> class Student(object): 2 ... def __init__(self, name): 3 ... self.name = name 4 ... 5 >>> print(Student('Michael')) 6 <__main__.Student object at 0x109afb190> 7 >>> class Student(object): 8 ... def __init__(self, name): 9 ... self.name = name10 ... def __str__(self):11 ... return 'Student object (name: %s)' % self.name12 ...13 >>> print(Student('Michael'))14 Student object (name: Michael)
__str__()
Returns the string that the user sees,__repr__()
Returns the string that the developer sees.
When Student ('Michael ') is called directly instead of print
<__main__.Student object at 0x109afb190>
In this case, you need to define another_ Repr _ (), and
_ Repr _ = _ str __
2: __iter _ (return an iteration object)
If a class is usedfor ... in
Loop, similar to list or tuple, you must implement__iter__()
Method. This method returns an iteration object. Then, the Python for loop will continuously call__next__()
Method to get the next value of the loopStopIteration
Exit the loop when an error occurs.
1 class Fib (object): 2 def _ init _ (self): 3 self. a, self. B = 0, 1 # initialize two counters a, B 4 5 def _ iter _ (self): 6 return self # The instance itself is an iteration object, therefore, def _ next _ (self): 9 self is returned. a, self. B = self. b, self. a + self. B # Calculate the next value 10 if self. a> 100000: # condition 11 raise StopIteration () 12 return self. a # return the next value 13 14 >>> for n in Fib (): 15... print (n) 16... 17 118 119 220 321 522... 23 4636824 75025
3: __getitem _ (for instance search/slice, etc)
The following example shows an _ getitem _ Implementation of index calculation.
1 class Fib(object): 2 def __getitem__(self, n): 3 a, b = 1, 1 4 for x in range(n): 5 a, b = b, a + b 6 return a 7 8 >>> f = Fib() 9 >>> f[0]10 111 >>> f[1]12 113 >>> f[2]14 215 >>> f[3]16 317 >>> f[10]18 89
IV: __getattr __
Under normal circumstances, if the method or attribute of the class does not exist, an error is returned. To avoid this error, you can write__getattr__()
Method to dynamically return an attribute.
1 class Student(object):2 3 def __init__(self):4 self.name = 'Michael'5 6 def __getattr__(self, attr):7 if attr=='score':8 return 99
When a non-existent property is called, for examplescore
, The Python interpreter will try to call__getattr__(self, 'score')
In this way, we have the opportunity to returnscore
Value:
1 >>> s = Student()2 >>> s.name3 'Michael'4 >>> s.score5 99
Of course, you can also return functions.
1 class Student(object):2 3 def __getattr__(self, attr):4 if attr=='age':5 return lambda: 25
The call method must be changed:
>>> s.age()25
This API is called only when no attribute is found.__getattr__
, Existing attributes, suchname
, Not in__getattr__
.
Any call, suchs.abc
Will returnNone
This is because we have defined__getattr__
The default return value isNone
. To make the class only respond to specific attributes, we need to throwAttributeError
Error:
1 class Student(object):2 3 def __getattr__(self, attr):4 if attr=='age':5 return lambda: 256 raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr)
In fact, all attributes and method calls of a class can be dynamically processed without any special means. Purpose: Write the SDK.
5: __ call __
An object instance can have its own attributes and Methods. When we call an instance method, we useinstance.method()
. However, define__call__()
Method, you can directly call the instance.
1 class Student(object):2 def __init__(self, name):3 self.name = name4 5 def __call__(self):6 print('My name is %s.' % self.name)
The call method is as follows:
1 >>> s = Student ('Michael ') 2 >>> s () # Do not input 3 My name is Michael in the self parameter.
The Callable function can determine whether an object can be called.
1 >>> callable(Student()) 2 True 3 >>> callable(max) 4 True 5 >>> callable([1, 2, 3]) 6 False 7 >>> callable(None) 8 False 9 >>> callable('str')10 False
Pytho also has a lot of customization class, link: http://docs.python.org/3/reference/datamodel.html#special-method-names