Python Custom Class Special methods

Source: Internet
Author: User
Tags gcd greatest common divisor

1. Special Methods

Defined in class

There is no need to call directly, some Python functions or operators will automatically call the corresponding special Method.

If the person class is defined and the instance of the person class is printed using the print P statement, A special method is called __str__ ()

You will need to implement this method in the person class at this Point.

Note When using special methods:

You just need to write a special method

Special methods that have relevance must be implemented (E.G. __getattr__,__setattr__,delattr__)

2. __str__ and __repr__ in Python

__str__ () is used to display to the user, while __repr__ () is used to display to the Developer.

Class Person (object):    def __init__ (self, name, gender):        self.name = name        Self.gender = Gender    def __str __ (self):        return ' (person:%s,%s) '% (self.name, self.gender)    __repr__ = __str__ #直接让repr和str相同

Once you have defined the repr function, you can output the Person's information by entering p directly to the command line during debugging, otherwise it will output

<__main__. Person object at 0x0000000002e66c88>

The __str__ and __repr__ functions are inherited by the quilt class.

3. __cmp__ in Python

To sort objects, You can use the function sorted function, provided the __cmp__ method of the class is Set.

Class Student (object):    def __init__ (self, name, score):        self.name = name        Self.score = Score    def __str__ (self):        return ' (%s:%s) '% (self.name, self.score)    __repr__ = __str__    def __cmp__ (self, s):        if Self.name < s.name:            return-1        elif self.name > S.name:            return 1        else:            return 0
>>> L = [Student (' Tim '), Student (' Bob ', Student),]>>> print sorted (L) [(alice:77), ( bob:88), (tim:99)]
4. __len__ in Python

Call Len () to return the length of the Instance.

Class Students (object):    def __init__ (self, *args):        self.names = args    def __len__ (self):        return len ( Self.names)
>>> ss = Students (' Bob ', ' Alice ', ' Tim ') >>> print len (ss) 3
Task:

The Fibonacci sequence is composed of 0, 1, 1, 2, 3, 5, 8 ...

Write a fib class in which Fib (10) represents the first 10 elements of the sequence, printFib prints the first 10 elements of an array, and Len (fib ) Returns the number of numbers 10 correctly.

Code Listing 1: (reference Code)

You can use STR () to convert an integer list to a string.

Class Fib (object):
def __init__ (self, num):
a, b, L = 0, 1, []
For n in range (num):
L.append (a)
a, B = b, A + b
Self.numbers = L

def __str__ (self):
Return STR (self.numbers)

__repr__ = __str__

def __len__ (self):
Return Len (self.numbers)

f = Fib (10)
Print F
Print Len (f)

Code 2: (written by Yourself)
Class Fib (object):    def __init__ (self, num):        self.num = num            def __str__ (self):        if (self.num==1):            return "[0]"        elif (self.num==2):            return "[0,1]"        else:            fib_str = "[0,"            fib=[0,1] for            K in Range (2,self.num+1):                fib_str = fib_str+ str (fib[k-1]) + ","                fib.append (fib[k-1]+fib[k-2])            return fib_ str[:-1]+ ' "    def __len__ (self):        return self.num   f = Fib (ten) print fprint len (f)
5. Mathematical operations in Python (operator Overloading)

Examples: rational numbers can be expressed in p/q, where P and q are Integers.

Call the GCD function (recursive) for greatest common divisor:

Euclidean theorem: if a=b*r+q, then GCD (a, b) =gcd (b,q)

def gcd (a, b):    if (b==0):        return a    return gcd (b,a%b) class Rational (object):    def __init__ (self, p, q):        SELF.P = p        self.q = q    def __add__ (self, r):        return Rational (SELF.P * r.q + self.q * r.p, self.q * R.q) 
   def __sub__ (self, r):        return Rational (self.p*r.q-r.p*self.q,self.q*r.q)    def __mul__ (self, r):        return rational (self.p*r.p,self.q*r.q)    def __div__ (self, r):        return Rational (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) print r1 + r2print r1-r2print R1 * R2print R1/R2
6. Type conversion in Python
The __int__ and __float__ methods implement type conversions,
The __str__ method can also be seen as a type Conversion.
Class Rational (object):    def __init__ (self, p, q):        self.p = p        self.q = q    def __int__ (self):        return SELF.P//SELF.Q    def __float__ (self):        return float (self.p)/float (self.q) print float (Rational (7, 2)) Print Float (Rational (1, 3))
7. @property in Python (adorner function overrides set and get METHOD)

The Get method is @property the modified Method.

The "@+ method name + dot +setter" is a fixed format used in conjunction with @property, set Method.

If you do not define a set method , you cannot assign a value to the property, and you can create a read-only Property.

Class Student (object):    def __init__ (self, name, score):        self.name = name        Self.__score = score    @ Property    def score (self):        return self.__score    @score. setter    def score (self, score):        if score < 0 or score >:            raise valueerror (' Invalid score ')        Self.__score = Score
8. __slots__ attribute restriction in Python

__SLOTS__ Specifies a list of properties allowed for a class. Adding properties outside the list is not Allowed.

Class Student (object):    __slots__ = (' name ', ' gender ', ' score ')    def __init__ (self, name, gender, score):        Self.name = name        Self.gender = gender        Self.score = Score
Forcibly adding the Grade property will cause an Error.
>>> s = Student (' Bob ', ' male ', ') >>> s.name = ' Tim ' # ok>>> s.score = # ok>>> s.gr ade = ' A ' Traceback (most recent call last):  ... Attributeerror: ' Student ' object has no attribute ' grade '
9. __call__ The class instance into a callable object in Python
Class Person (object):    def __init__ (self, name, gender):        self.name = name        Self.gender = Gender    def __ call__ (self, friend): "        print ' My name is%s ... '% self.name        print ' My friend is%s ... '% friend
>>> p = person (' bob ', ' male ') >>> p (' Tim ') My name is Bob ... My Friend is Tim ...
In the fourth section of the Fibonacci sequence, you can use call implementation Instead.
Class Fib (object):            def __call__ (self,num):        a=0        b=1        l=[] for           N in range (1,num+1):            l.append (a              temp = b                        B = a + b            A = temp              return L            f = Fib () print f (10)
Reference code:
Class Fib (object):    def __call__ (self, num):        a, b, L = 0, 1, [] for        N in range (num):            l.append (a)            a, b = b, A + b        return Lf = Fib () print f (10)

Note that the highlighted statement in the code, using the reference code, saves an intermediate variable.

Python Custom Class Special methods

Related Article

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.