Python Learning Custom Classes

Source: Internet
Author: User

This article and everyone to share is mainly the Python development in the custom class related content, together to look at it, hope to learn from you and use this part of the content is helpful.1. What is a special method in PythonAn instance of any data type has a special method:__str__ ()· For print.__str__· For Len.__len__· Used in CMP__cmp__·  Special method definition in class · No need to call directly ·  Some Python functions or operators call the corresponding special method file:///c:\users\wlc\appdata\local\temp\ksohtml\wps8b49.tmp.jpg to implement the special method correctly ·  You only need to write a special method of use · Special methods that have relevance must be implemented ·__getattr__,__setattr__,__delattr__2. Python in __str__ and __repr__class Person(object):def__init__(Self, Name, gender): Self.name = Nameself.gender = GenderclassStudent(person):def__init__(Self, name, gender, score): Super (Student, self). __INIT__ (name, gender) Self.score = Scoredef__str__(self):return' (Student:%s,%s,%s) '% (Self.name, Self.gender, self.score) __repr__ = __str__s = Student (' Bob ', ' Male ', 88)PrintS3. Python in __cmp__When sorting built-in data types such as int, str, Python's sorted () is sorted by the default comparison function CMP, but if you sort an instance of a group of Student classes, you must provide our own special method__cmp__ ()class Student(object):def__init__(self, Name, score): Self.name = Nameself.score = Scoredef__str__(self):return' (%s:%s) '% (Self.name, self.score) __repr__ = __str__def__cmp__(self, s):ifSelf.name < s.name:return-1elifSelf.name > S.name:return1Else:return0classStudent(object):def__init__(self, Name, score): Self.name = Nameself.score = Scoredef__str__(self):return' (%s:%s) '% (Self.name, self.score) __repr__ = __str__def__cmp__(self, s):ifSelf.score = = S.score:returnCMP (Self.name, S.name)return-CMP (Self.score, s.score) L = [Student (' Tim ',), Student (' Bob ', N), Student (' Alice ', 99)]PrintSorted (L)4. Python in __len__If a class behaves like a list, the Len () function is required to get the number of elements. To make the Len () function work, the class must provide a special method, __len__ (), which returns the number of elements.classStudents(object):def__init__(Self, *args): Self.names = argsdef__len__(self):returnLen (self.names) ss = Students (' Bob ', ' Alice ', ' Tim ')PrintLen (ss) # 3classFib(object):def __init__(Self, num): A, B, L = 0, 1, [] forNinchRange (num): L.append (a) A, B = B, a + Bself.num = Ldef__len__(self):returnLen (self.num) F = Fib (10)PrintF.num # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]PrintLen (f) # 105. Mathematical operations in PythonThe basic data types provided by Python int, float can do integer and floating point arithmetic, and the exponentiation operation.defGCD(A, B):ifb = = 0:returnAreturnGCD (b, a% b)classRational(object):def__init__(Self, p, q): SELF.P = PSELF.Q = qdef__add__(Self, R):returnRational (SELF.P * r.q + self.q * r.p, SELF.Q * r.q)def__sub__(Self, R):returnRational (SELF.P * r.q-self.q * r.p, SELF.Q * r.q)def__mul__(Self, R):returnRational (SELF.P * r.p, SELF.Q * r.q)def__div__(Self, R):returnRational (SELF.P * r.q, SELF.Q * r.p)def__str__(self): g = gcd (SELF.P, SELF.Q)return'%s/%s '% (self.p/g, self.q/g) __repr__ = __STR__R1 = Rational (1, 2) r2 = rational (1, 4)PrintR1 + R2PrintR1-r2PrintR1 * R2PrintR1/r26. Type conversion in PythonPrintint (12.34) # 12PrintFloat (12) # 12.0classRational(object):def__init__(Self, p, q): SELF.P = PSELF.Q = qdef__int__(self):returnSELF.P//SELF.Qdef__float__(self):returnFloat (SELF.P)/SELF.QPrintFloat (Rational (7, 2) # 3.5PrintFloat (Rational (1, 3) # 0.3333333333337. @property in PythonclassStudent(object):def__init__(self, Name, score): Self.name = Nameself.__score = Score@propertydefscore(self):returnSelf.__score@score.setterdefscore(Self, score):ifScore < 0orScore > 100:RaiseValueError (' invalid score ') Self.__score = Score@propertydefGrade(self):ifSelf.score < 60:returnCifSelf.score < 80:returnBreturn' A ' s = Student (' Bob ', 59)PrintS.grades.score = 60PrintS.grades.score = 99PrintS.grade8. Python in __slots__The purpose of slots is to limit the properties that the current class can have, and if you do not need to add any dynamic properties, using __slots__ can also save memory.classStudent(object): __slots__ = (' name ', ' gender ', ' score ')def__init__(Self, name, gender, score): Self.name = Nameself.gender = Genderself.score = scores = Student (' Bob ', ' Male ', ') S.name = ' Tim ' # oks.score = oks.grade # = ' A ' # Errorclass Person(object): __slots__ = (' name ', ' gender ')def__init__(Self, Name, gender): Self.name = Nameself.gender = GenderclassStudent(person): __slots__ = {' Score '}def__init__(Self, name, gender, score): Super (Student, self). __INIT__ (name, gender) Self.score = scores = Student (' Bob ', ' Male ', ()) s. name = ' Tim ' S.score = 99PrintS.score9. Python in __call__A class instance can also become a callable object, just to implement a special method__call__ ()class Person(object):def__init__(Self, Name, gender): Self.name = Nameself.gender = Genderdef__call__(Self, Friend):Print' My name is%s ... '% self.namePrint' My friend is%s ... '% FRIENDP = person (' bob ', ' Male ') p (' Tim ') # My name is Bob ... My Friend is Tim ...classFib(object):def__call__(Self, num): A, B, L = 0, 1, [] forNinchRange (num): L.append (a) A, B = B, A + breturnLf = Fib ()PrintF (10) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] Source: Blog Park

Python Learning Custom Classes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.