Here is a note of some of the knowledge about class in Python. What is not understood without explanation means that the explanation is not understood.
Class knowledge in Python the attribute references and instances of classes
classMyClass ():" "A simple Exampel class" "I= 12345#class variable shared by all instances def __init__(self, Realpart, Imagpart): Self.real= Realpart#instance variable unique to each instanceSelf.imag =Imagpartdeff (self):returnSelf.real +'Hello'x= MyClass ('Huhx','Linux')Print(X.real, X.imag, x.i, myclass.i)#Myclass.real will make an error .Print(MyClass.__doc__X.__doc__)#A simple Exampel classPrint(MYCLASS.F (x), X.F ())#Huhxhello Huhxhello
- When a-class defines an __init__ () method, class instantiation automatically invokes __init__ () for the newly-created Clas s instance. The __init__ () method of the Python class is similar to the constructor method in Java.
- The attribute I of the MyClass class is shared among all instances of MyClass, and real and Imag are instance private, and the values of each MyClass instance may be different. For this, take a look at the following example
1 classDog ():2Tricks = []3 4 #def __init__ (self):5 #self.tricks = []6 7 defadd_tricks (self, trick):8 self.tricks.append (Trick)9D =Dog ()TenD.add_tricks (' Roll Over') OneE =Dog () AE.add_tricks ('Play Dead') - Print(D.tricks, E.tricks)#[' Roll over ', ' play Dead '] [' Roll over ', ' play dead ']
If you comment out the second line, open 4, 5 lines. The result of the operation: [' Roll over '] [' play dead ']. The methods of the class can also be defined outside the class, and the test cases are as follows:
defF1 (self, x, y):returnmin (x, y)classC (): F=F1defg (self):return 'Hello World'h=GCLASSC=C ()Print(C.F (ClassC, 2,), CLASSC.F (2, 45))#2 2Print(ClassC.h ())#Hello WorldClassC.h ='Hello ABC'Print(CLASSC.G (), classC.h)#Hello World Hello ABC
The above example can see that F1 is defined outside of Class C and can be used normally. Also, assign H = g in the class and modify the value of H. Does not affect G, the method assignment in the description class is a value pass.
Second, the Python class inheritance and access rights
Python inherits the following syntax, which can support multiple layers of inheritance.
class derivedclassname (Base1, Base2, Base3): <statement-1> ... <statement-N>
For private variables of Python, provide the following code:
classStudent (object):def __init__(self, Name, score): Self.__name=name self.__score=score Self._name=namedefPrint_score (self):Print('%s:%s'% (self.__name, self.__score)) Bart= Student ('Bart Simpson', 59)#print (bart.__name) # attributeerror: ' Student ' object has no attribute ' _name 'Print(Bart._student__name)Print(Bart._name)the contract is externally inaccessible, but can actually be accessed externally. Print(Type (BART))#<class ' __main__. Student ' >Print(Isinstance (Bart, Student), Issubclass (Student, Object))#true True
You can define an empty class in Python, and the properties and methods can be added by themselves.
class Employee: Pass = Employee () # Create a empty Employee record# Fill The fields of the record< /c9>'John Doe'computer lab' =print# John Doe
Iii. generators and iterators in Python class
# One-off forEleinch[1, 2, 3]: Print(Ele, end=' ')Print()#ITERs ='ABC'it=ITER (s)Print(Next (IT), next (IT), next (IT), end=' ')Print()#GeneratorsdefReverse (data): forIndexinchRange (len (data)-1,-1, 1): yieldData[index] forCharinchReverse'Huhx'): Print(Char, end=' ')Print()#class Next and IterclassReverse:"""Iterator for looping over a sequence backwards.""" def __init__(self, data): Self.data=Data Self.index=len (data)def __iter__(self):return Selfdef __next__(self):ifSelf.index = =0:Raisestopiteration Self.index= Self.index-1returnSelf.data[self.index]rev= Reverse ('Linux') forCharinchRev:Print(Char, end=' ')#1 2 3#a b c#x H u h#x u n i l
Iv. some special methods of Python class
Python allows you to define a special __slots__ variable when defining a class to limit the attributes that the class instance can add:
class Student (object): __slots__ = ('name'' age'= ' Huhx ' =45
Operation will be error:
Traceback (most recent): " g:/java/go/program/2017-05-18/learnpython1/test10/huhx5.py " in <module> ="Student" Score'
Python's built-in @property decorator is responsible for turning a method into a property invocation. When a non-existent property is called, such as the Score,python interpreter, it attempts to invoke __getattr__ (self, ' score ') to try to obtain the property. The __str__ () method is similar to the ToString method in a Java class. The following cases
classStudent (object): @propertydefscore (self):return 'score ='+Str (self._score) @score. Setterdefscore (self, value):if notisinstance (value, int):RaiseValueError ('score must is an integer!') ifValue < 0orValue > 100: RaiseValueError ('score must between 0 ~ 100!') Self._score=valuedef __str__(self):return 'Student Info:'+Self.scoredef __getattr__(self, item):ifitem = ='Address': return ' China' elifitem = ='Attr_fun': return LambdaX:X *XS=Student () S.score= 60Print(S.score)#score =Print(s.address)# ChinaPrint(S.attr_fun (4))# -Print(s)#Student Info:score =S.score = 999#Throw Exception
Friendship Link
Python Basics---->python use (vi)