Python tip 31 [Python tip2]

Source: Internet
Author: User

 

1. Problems and Solutions when the default value of the function is mutable

Def F2 (A, L = []):
L. append ()
Return L
Print (F2 (1 ))
Print (F2 (2 ))
Print (F2 (3 ))
Def F3 (A, L = none ):
If l is none:
L = []
L. append ()
Return L
Print (F3 (1 ))
Print (F3 (2 ))
Print (F3 (3 ))
# The result will be
# [1]
# [1, 2]
# [1, 2, 3]
# [1]
# [2]
# [3] From copy import deepcopy
Def resetdefaults (f ):
Defaults = f. _ defaults __
Def resetter (* ARGs, ** kwds ):
F. _ defaults _ = deepcopy (defaults)
Return F (* ARGs, ** kwds)

Resetter. _ name _ = f. _ name __
Return resetter

@ Resetdefaults # This is how you apply a decorator
Def testdefacorcorrect (item, stuff = []):
Stuff. append (item)
Print (stuff)

Testdefacorcorrect (1)
# Prints '[1]'
Testdefacorcorrect (2)
# Prints '[2]', as expected

 

 

2 function decoration Mode

Def decorator1 (func ):
Return lambda: func () + 1

Def decorator2 (func ):
Def print_func ():
Print (func ())
Return print_func

@ Decorator2
@ Decorator1
Def function ():
Return 41

# To cal functions (), it is equal to call decorator2 (decorator1 (function ))

Function ()
# Prints '42'

 

 

3. Check whether the type attributes and methods exist.

Class class:
Answer = 42

Getattr (class, 'answer ')
# Returns 42
Getattr (class, 'Question ', 'What is six times nine? ')
# Returns 'what is six times nine? '
Getattr (class, 'Question ')
# Raises attributeerror

 

 

4. dynamically modify functions in the class

Class class:
Def method (Self ):
Print ('Hey A method ')

Instance = Class ()
Instance. Method ()
# Prints 'Hey A Method'

Def new_method (Self ):
Print ('new method wins! ')

Class. method = new_method
Instance. Method ()
# Prints 'new method wins! '

 

 

Use of Class 5 static methods

Class class:
@ Classmethod
Def a_class_method (CLS ):
Print ('I was called from Class % s' % CLs)

@ Staticmethod
Def a_static_method ():
Print ('I have no idea where I was called from ')

Def another_static_method ():
Print ('I have no idea where I was called from2 ')

Def an_instance_method (Self ):
Print ('I was called from the instance % s' % self)

Instance = Class ()

Class. a_class_method ()
Instance. a_class_method ()
# Both print 'I was called from class _ main _. class'

Class. a_static_method ()
Instance. a_static_method ()
# Both print 'I have no idea where I was called from'

Class. another_static_method ()
# Both print 'I have no idea where I was called from2'
# Instance. another_static_method ()
# Typeerror: another_static_method () takes no arguments (1 given)

# Class. an_instance_method ()
# Typeerror: an_instance_method () Takes exactly 1 positional argument (0 given)
Instance. an_instance_method ()
# Prints something like 'I was called from the instance <__ main _. class instance at 0x2e80d0>'

 

6. Use main as the python file Portal

If _ name _ = "_ main __":

 

7. Redirect function output to a file (the following code has a bug)

Import sys

Def stdouttofile (filename, function, argS ):
Oldstdout = SYS. stdout
F = open (filename, "W ")
SYS. stdout = f
Function (ARGs)
# SYS. stdout. Flush ()
# F. Close ()
SYS. stdout = oldstdout

If _ name __= = '_ main __':
Print ("modules ")
Stdouttofile ("modules.txt", help, "modules ")
Print ("builtins ")
Stdouttofile ("builtins.txt", help, "builtins ")
Print ("keywords ")
Stdouttofile ("keyword.txt", help, "keywords ")

 

 

 

Reference: http://www.siafoo.net/article/52#id26

 

Complete!

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.