Python Learning Day 17th-Custom Classes

Source: Internet
Author: User

What is a custom class?

Python's class allows you to define a number of special methods that make it very easy to generate specific classes. A special way to apply or rewrite Python in a class is to get a class that is a custom class.

We all know the use of print. See the example below

>>> lst = [2,3,4]print  lst[2, 3, 4]class  Animal (object):     Pass>>> a = Animal ()print  a<__main__. Animal Object at 0x01e6e990>

Why does print recognize the data types of LST and p?

When we execute the following code, we know why?

Print lst. __str__ ' __str__ ' print A.__str__'__str__' of Animal object at 0x01e6e990>

__str__ a special method to identify each data type. If you want an instance of the class, print a prints out ' object of Animal class '. What do I do? Redefine the __str__ method.

class Animal (object):     def __str__ (self):         return ' object of Animal class '    >>> a = Animal ()printclass

But sometimes we find that knocking directly

>>> a<__main__. Animal Object at 0x01e6e990>

__STR__ will not be called. Because when a direct knock on the line of code, the direct call is not __str__. But __repr__.

class Animal (object):     def __str__ (self):         return ' object of Animal class '    __repr__ __str__//lazy for a bit    >>> a = Animal ()>>>class

Python has a lot of special methods, and we don't introduce them here. The following is mainly about __slots__,__call__, @property usage.

__slots__

Python is a dynamic language that can dynamically add properties of an instance during any instance that can be run. However, sometimes you want to restrict the addition of an instance's properties by using the __slot__ method. See the following example:

>>>classPerson (object):__slots__= ('name',' Age')//Limit properties only for name and agedef __init__(self,name,age): Self.name=name Self.age= Age>>> p = person ('Zhangsan', 25)>>>P.age25>>>P.name'Zhangsan'>>> P.gender ='Mans'///Direct dynamic assignment of attribute gender, error will occurTraceback (most recent): File"<pyshell#42>", Line 1,inch<module>P.gender='Mans'Attributeerror:' Person'object has no attribute'Gender'

The purpose of __slot__ is to limit the properties that the current class can have. Therefore, in an inherited environment, subclasses are unaffected.

 >>> class   Student (person):  pass  >>> s = Student ( " Span style= "color: #800000;" >zhangsan  , 26)  >>>< Span style= "color: #000000;" > S.age  26>>> S.name  "  Span style= "color: #800000;" >zhangsan   " >>> S.gender =  man   "// >>> S.gender  "  man    

So subclass student If you want to restrict the addition of attributes, but also through the __slots__ to control.

__call__

An instance of a class can become a callable object, just to implement a special method __call__.

Next we turn the student class into a callable object:

>>>classStudent (person):def __init__(Self,name,score): Self.name=name Self.score=score>>>classStudent (person):def __init__(Self,name,score): Self.name=name Self.score=scoredef __call__(self,age):Print 'My name is%s'%Self.namePrint 'My age is%d'% Age>>> s = Student ('Lixi', 89)>>> S (25) My name isLiximy Age is25

Sometimes you'll find S (25) At first glance it doesn't feel like a function or an instance of an object. Instances of Python language functions and objects are not distinct.

@property

In the class student above, when modifying the score value of the S instance,

>>> S.score = 89>>> S.score = 9999

However, it is not possible to check the score validity of an S instance. This can only be done at this time:

>>>classStudent (object):def __init__(Self,name,score): Self.name=name self.__score=scoredefSet_score (self,score):ifScore <0orScore >100:            RaiseValueError ('Invalid score') self.__score=scoredefGet_score (self):returnSelf.__score>>> s = Student ('Wangwu', 89)>>> S.set_score (89)>>> S.set_score (9999)//illegal value, Valueerrortraceback (most recent call last): File"<pyshell#75>", Line 1,inch<module>S.set_score (9999) File"<pyshell#71>", Line 7,inchSet_scoreRaiseValueError ('Invalid score') Valueerror:invalid score

Sometimes feel write S.set_score and S.get_score not directly write S.score so direct. Is there any other way? Can both direct s.score and check the effectiveness of score? Python provides an adorner for functional requirements such as @property high-order functions.

>>>classStudent (object):def __init__(Self,name,score): Self.name=name self.__score=score @propertydefscore (self):returnSelf.__score@score. Setterdefscore (self,score):ifScore <0orScore >100:            RaiseValueError ('Invalid score') self.__score=score>>> s = Student ('Liunx', 98)>>> S.score = 89>>> S.score = 9999Traceback (most recent): File"<pyshell#82>", Line 1,inch<module>S.score= 9999File"<pyshell#79>", Line 12,inchscoreRaiseValueError ('Invalid score') Valueerror:invalid score

Summary:

Special methods:

1. Any data instance has a special method

2. Special method defined in class

3. No need to call directly

Some methods or functions of 4.python call a special method of data instance directly

To implement a special method:

1. Re-writing the special methods used

2. If special methods are re-selected, some of the associated special methods will be implemented together. Example: __setattr__,__getattr__,__delattr__

Python Learning Day 17th-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.