Python Advanced--04 How to customize a class

Source: Internet
Author: User

1. Magic Method-Definition

defined in a class (such as __len__ in __str__,list in object), do not need to call the method directly,some functions or operators in Python call the corresponding special method (such as print call __str__,len () call __len__, and so on), any derived class of that class can customize the functionality of these methods by overriding these special methods.

2. Magic Method-Rewriting principle

Write only the special methods used

special methods of relevance must be implemented (e.g. __getattr__, __setattr__, __delattr__)

3. Magic Method--attribute-related

The GET, set, Del methods of the constructed property

Method One:

Write his own get, set, Del method, and provide for external use, through the specified set, get method to assign value, take value

Class Student (object):

def __init__ (self, Name, score):

Self.name = Name

Self.__score = Score

def get_score (self):

Return Self.__score

def set_score (self, score):

If score < 0 or score > 100:

Raise ValueError (' Invalid score ')

Self.__score = Score

Method Two:

Using the property, setter, getter method, or adorner, the external can use the attribute name directly to assign, value, and do not have to pass the specified set, get method

4. Special methods-Examples of Class 4.1 methods __new__ (CLS, *args,**kw)

Typically used to control the process of generating a new instance , which is a class-level method.

4.2 Example Method __init__ (SELF,*ARGS,**KW)

controls the process of initializing a new instance . Custom Instance = class name (*args,**kw)

__del__ (self)

Customizing thedel object method

4.3 Printing related __str__ (self)

Customizing thePrint instance or thestr (instance)method

__REPR__ (s)

Used directly when entering objects in an interactive row

4.4s.attr mode access __getattr__ (s, name)

Customizing the " instance. Name" method

__SETATTR__ (S, name, Val)

Customizing the " instance. Name=val" method

__DELATTR__ (s, name)

Customizing the "del instance. Name" method

4.5 Construct sequence __len__ (self)

Customizing thelen (instance)method

__getitem__ (Self,key)

Customizing the instance [key]method

__setitem__ (Self,key,value)

Customizing the instance [Key]=value] Method

__delitem__ (Self,key)

Customizing the "del instance [key]" method

4.6 Construct iterator __iter__ (self) __next__ (self)

Customizing the For-TMP in instance method

http://www.maiziedu.com/wiki/python/special/

4.7 Construction Comparable class _lt_ ()

Customizing the instances < instances method

_le_ ()

Customizing the instance <= instance method

_gt_ ()

Customizing the instances > Instances method

_ge_ ()

Customizing the instance >= instance method

_eq_ ()

Customizing the instance = = Instance method

_ne_ ()

Customizing the instance! = Instance method

__cmp__ (self, other)

Custom "sorted ([instance 1, Instance 2,...])" method

4.8 Construct operational Class _add_ ()

Customizing the instance + instance method

_sub_ ()

Customizing the instance-instance method

_mul_ ()

Customizing the instance instance method

_div_ ()

Customizing the instance/instance method

http://www.maiziedu.com/wiki/python/special/

4.9 Conversion Type __int__

customizing theint (instance)method

__float__

Customizing thefloat (instance)method

4.10 Other __slots__

The goal is to limit the properties (tuple form) that the current class can have , and if you do not need to add any dynamic attributes, you can save memory with __slots__.

Class Student (object):

__slots__ = (' name ', ' gender ', ' score ')

def __init__ (self, name, gender, score):

Self.name = Name

Self.gender = Gender

Self.score = Score

# Now, take action on the instance:

>>> s = Student (' Bob ', ' Male ', 59)

>>> s.name = ' Tim ' # OK

>>> S.score = # OK

>>> s.grade = ' A '

Traceback (most recent):

...

Attributeerror: ' Student ' object has no attribute ' grade '

__call__

A custom instance (XX)method, similar to a function call .

Class Fib (object):

def __init__ (self):

Pass

def __call__ (Self,num):

If num<0:

Raise ValueError (' Invalid score ')

L=[]

L.append (0)

If num==1:

Return L

L.append (1)

If num ==2:

Return L

For I in Range (3,num+1):

L.append (L[-1]+l[-2])

Return L

f = Fib ()

Print F (10)

__hash__ (s)

Custom " instance 1 is instance 2", "instance 1 = = Instance 2" and other methods

Http://www.cnblogs.com/pengsixiong/p/5381850.html

__NONZERO__ (s)

To convert an object to a Boolean value, customize the "If instance:" method

5. Special Statement 5.1EXEC statement

Used to execute a python statement stored in a string or file . For example, we can generate a string that contains Python code at run time, and then execute the statements using the EXEC statement.

The following is a simple example.

>>> exec ' print ' Hello world '

Hello World

5.2eval statements

Used to calculate a valid python expression stored in a string . The following is a simple example.

>>> eval (' 2*3 ')

6

5.3assert statements

An Assert statement is used to declare that a condition is true . For example, if you are very confident that there is at least one element in the list you are using, and you want to test this and throw an error when it is not true, then the Assert statement is the ideal statement to apply in this case. when an Assert statement fails, a assertionerror is raised.

>>> mylist = [' Item ']

>>> assert Len (mylist) >= 1

>>> Mylist.pop ()

' Item '

>>> assert Len (mylist) >= 1

Traceback (most recent):

File "", Line 1, in?

Assertionerror

5.4raise statements

Throwing Exceptions manually

Raise ValueError (' Invalid score ')

6. Detailed properties in Appendix 6.1python

you can implement a read-only property (without setting the Set method), and a custom action at the same time as the set, get, Del properties.

http://python.jobbole.com/80955/

The difference between 6.2__new__ (cls,*args,**kw) and __init__ (SELF,*ARGS,**KW)

Http://www.cnblogs.com/ifantastic/p/3175735.html

Python Advanced--04 How to customize a class

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.