Python Study Notes (7) and python Study Notes
1. dynamically add attributes and methods to a class:
1. dynamically add attributes and methods to an instance:
The method bound to an instance does not work for another instance.
Class Student (object): passs = Student () s. name = 'Michael '# dynamically bind an attribute print s to the instance. namedef set_age (self, age): # define a function as the instance method self. age = age from types import MethodTypes. set_age = MethodType (set_age, s, Student) # bind a method s to the instance. set_age (25) # Call the instance method print s. age # Test Result
2. dynamically add attributes and methods to a class:
class Student(object): passs = Student()from types import MethodTypedef set_score(self, score): self.score = score Student.set_score = MethodType(set_score, None, Student)s.set_score(100)print s.score
2. Use _ slots __
You can use _ slots _ to restrict attributes that can be added to a class:
Class Student (object): _ slots _ = ('name', 'age') # Use tuple to define the property name s = Student () that can be bound () # create a new instance s. name = 'Michael '# bind the attribute 'name' s. age = 25 # bind the property 'age'
Note: The properties defined by __slots _ only work for the current class and do not work for the inherited subclass.
3. Use @ property
@ Property is responsible for calling a method into a property:
Class Student (object): @ property def score (self): return self. _ score @ score. setter def score (self, value): if not isinstance (value, int): raise ValueError ('score must be an integer! ') If value <0 or value> 100: raise ValueError ('score must between 0 ~ 100! ') Self. _ score = value s = Student () s. score = 60 # OK, actually converted to s. set_score (60) print s. score # OK, actually converted to s. get_score ()
Iv. Multi-inheritance:
Python allows multiple inheritance. For example, Dog inherits Animal and Runnable.
class Animal(object): passclass Runnable(object): def run(self): print('Running...') class Dog(Animal, Runnable): pass
V. customization:
1. _ str __
Equivalent to toString in java
class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'Student object (name: %s)' % self.nameprint Student('Michael') # Student object (name: Michael)
2. _ iter __
If a class wants to become list or tuple, it can be cyclically (.. in), the _ iter _ method must be implemented. This method returns an iteration object and continuously calls the next () method of the iteration object to get the next value of the Loop:
Class Fib (object): def _ init _ (self): self. a, self. B = 0, 1 # initialize two counters a and B def _ iter _ (self): return self # The instance itself is an iteration object, so it returns its own def next (self ): self. a, self. B = self. b, self. a + self. B # Calculate the next value if self. a> 100000: # exit loop condition raise StopIteration (); return self. a # return the next value for n in Fib (): print n
3. _ getitem __
To obtain elements by subscript, implement _ getitem __
Class Fib (object): def _ init _ (self): self. a, self. B = 0, 1 # initialize two counters a, B class Fib (object): def _ getitem _ (self, n): a, B = 1, 1 for x in range (n): a, B = B, a + B return af = Fib () print f [0]
4. _ getattr __
To dynamically return an attribute, implement _ getattr __
For example, when a nonexistent attribute score is called, python tries to call _ getattr _ (self, 'score ') to obtain the attribute.
class Student(object): def __init__(self): self.name = 'Michael' def __getattr__(self, attr): if attr=='score': return 99s = Student()print s.name # 'Michael'print s.score # 99
5. _ call __
Call class itself:
class Student(object): def __init__(self, name): self.name = name def __call__(self): print('My name is %s.' % self.name) s = Student('Michael')print s() # My name is Michael.
6. use metadata:
1. type ()
The type () function allows you to view the type of a class or a variable.
The type () function can also create a new type: for example, to create a Hello class
Def fn (self, name = 'World'): # define the function print ('hello, % s. '% name) Hello = type ('hello', (object,), dict (Hello = fn) # create hello classh = Hello () print h. hello () # Hello, world. print (type (Hello) # <type 'type'> print (type (h) # <class '_ main __. hello '>
To create a class object, the type () function will input three parameters in sequence:
1) class Name
2) The inherited parent class set. Note that python supports multiple inheritance. If there is only one parent class, do not forget the single-element method of tuple.
3) The method name of the class is bound to the function. Here we bind the function fn to the method name hello.
2. metaclass
Metadatabase-it is estimated that this stuff is similar to the java class.