Python note 7# object-oriented Advanced Programming II

Source: Internet
Author: User

▲ Custom Class

Python has a number of special-purpose functions like __slots__ that can help us customize the class.

Official Document Link: https://docs.python.org/3.4/reference/datamodel.html#special-method-names

1) __str__ and __repr__

The sample code is as follows:

>>>classStudent (object): ...def __init__(self, name): ... self.name=name ...>>> stu1 = Student ('Jack')>>>STU1<__main__. Student Object at 0x01740e70>>>>Print(STU1)<__main__. Student Object at 0x01740e70>>>>classStudent (object): ...def __init__(self, name): ... self.name=name#print (STU1) calls the __str__ method, returning the string that the user sees...def __str__(self): ...return 'Student Object (name:%s)'%self.name ...>>> stu1 = Student ('Rose')>>>STU1<__main__. Student Object at 0x0174a030>>>>Print(STU1) Student object (name:rose)>>>classStudent (object): ...def __init__(self, name): ... self.name=name ...def __str__(self): ...return 'Student Object (name:%s)'%Self.name#STU1 calls the __repr__ method and returns the string that the developer sees...__repr__=__str__...>>> stu1 = Student ('Michael')>>>Stu1student Object (Name:michael)>>>Print(STU1) Student object (Name:michael)

2) __iter__ and __getitem__ ()

If a class wants to be like a list or a tuple, it can be used for: In.. Loop, the __iter__ () method needs to be implemented. The method returns an iterative object (which must be self), and the For loop constantly calls the class instance's Loop method __next__ () to get the next value until it exits the loop.

The __getitem__ () method needs to be implemented if an instance is required to take out elements as a list, as follows.

The sample code is as follows:

#Coding:utf-8#Create a fib sequence iteratorclassFib (object):def __init__(self): SELF.A, self.b= 0, 1#The instance itself is an iterator that returns itself    def __iter__(self):return Self#Python3 The next () method to __next__ ()    def __next__(self): SELF.A, self.b= self.b, SELF.A +self.bifSELF.A > 500:            Raisestopiteration (); returnSELF.A#__getitem__ () can receive integers integer and slice slice    def __getitem__(self, n):ifisinstance (n, int): A, B= 1, 1 forXinchrange (N): A, B= B, A +breturnaifisinstance (n, Slice): Start=N.start Stop=N.stop A, b= 1, 1L= []             forXinchRange (stop):ifX >=Start:l.append (a) A, B= B, A +breturnL forIinchFib ():Print(i)Print('-'* 50)Print(Fib () [5])Print('-'* 50)Print(Fib () [5:10])

Operation Result:

1123581321345589144233377--------------------------------------------------8---------------------------------- ----------------[8, 13, 21, 34, 55]

3) __getattr__

An error occurs when the property or method of the called class does not exist. But we use the __getattr__ () method to write a dynamic return property or method.

It is only found in __getattr__ if no property or method is located. __getattr__ () returns none by default.

4) __call__

An object can be called by its own properties and methods, which we call methods generally through Instance.method (). If you want to implement calls on the instance itself, you need to define the __call__ () method.

The callable () can be used to determine whether an object itself is callable.

▲ meta-class Metaclass

Python note 7# object-oriented Advanced Programming II

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.