Statement: Resources from the MU-class network Python Learning course, the following is only a summary of individual learning, for reference only
Special methods for 1.Python classes
Features: Methods that begin and end with __ , such as __str__ () for print, __getattr__ (), __setattr__ (), etc.
There is no need to call directly in code, and some Python functions and operators are called automatically.
You can customize the implementation, such as the __str__ () method
classPerson (object):def __init__(self,name,gender): Self.name=name Self.gender=Genderdef __str__(self):return '(Person:%s,%s)'%(Self.name,self.gender)PrintPerson ("Roger","Male")
Python defines the __str__ () and __repr__ () two methods, which are displayed to the user, which is displayed to the developer, so if __str__ () is modified under the interactive command line, then the call may not be modified but the __repr__ () is called. You can also make the same two methods: __repr__ = __str__
2. Special Setter and Getter
In Python, the setter and getter can be written by the adorner, making the call more straightforward, and, of course, using Java in a similar way. Because Python supports higher-order functions, the Get/set method can be decorated with adorners as attributes.
classStudent (object):def __init__(self, Name, score): Self.name=name self.__score=score @property#Decorate Get method defscore (self):returnSelf.__score@score. Setter#Decorative Set method, a byproduct of @property decoration defscore (self, score):ifScore < 0orScore > 100: RaiseValueError ('Invalid score') self.__score=score#after decorating, you can set the score as you would with the propertiess = Student ("Bob", 59) S.score= 60PrintS.scores.score= 1000PrintS.score#There will be exceptions, because the scope of the score is checked.
3. Restrict the properties that the current class can have: __slots__
class Student (object): __slots__ = ('name''gender'Score ') def__init__(self, name, gender, score): = name = gender = Score
4. Callable objects (objects can also be called)
In Python, a function is an object, called a callable object, and an instance of a class can become a callable object, just to implement a special method __call__()
class Person (object): def __init__ (self,name,gender): = name = gender def__call__(self, *args, **kwargs): # Implement the __call__ method so that the instance can be called print args
class Fib (object): def __call__ (self, num): = 0, 1, [] for in Range (num): l.append (a) = B, A + b
return= Fib ()print f (10)
Object-oriented programming in Python simple summary 3--custom classes