在Python中使用装饰器进行类型检查 [英] Using Decorators in Python for Type Checking

查看:122
本文介绍了在Python中使用装饰器进行类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更多是语法错误问题,我正在尝试在Python Decorators上完成本教程



http://www.learnpython.org/page/Decorators



我的尝试密码

  def Type_Check(correct_type):
def new_function(old_function):
def another_newfunction(arg):
if(isintance(arg,correct_type)):
return old_function(arg)
else:
print Bad Type

#此处输入代码

@Type_Check(int)
def Times2(num):
返回num * 2

print Times2(2)
Times2('Not A Number')

@Type_Check(str)
def First_Letter(word):
返回字[0]

打印First_Letter('Hello World' )
First_Letter(['Not','A','String'])

我想知道怎么了,请帮忙

解决方案

似乎您忘了在装饰器的末尾返回新定义的函数:

  def Type_Check( correct_type):
def new_function(old_function):
def another_newfunction(arg):
if(isinstance(arg,correct_type)):
return old_function(arg)
否则:
打印错误类型
返回another_newfunction
返回new_function

编辑:还有一些类型,由安德烈(Andrean)修复


This is more of a syntax error issue, I am trying to do this tutorial on Python Decorators

http://www.learnpython.org/page/Decorators

My Attempted Code

def Type_Check(correct_type):
    def new_function(old_function):
        def another_newfunction(arg):
            if(isintance(arg, correct_type)):
                return old_function(arg)
            else:
                print "Bad Type"

    #put code here

@Type_Check(int)
def Times2(num):
    return num*2

print Times2(2)
Times2('Not A Number')

@Type_Check(str)
def First_Letter(word):
    return word[0]

print First_Letter('Hello World')
First_Letter(['Not', 'A', 'String'])

I am wondering whats wrong, please help

解决方案

It looks like you forgot to return the newly defined function at the end of the decorator :

def Type_Check(correct_type):
    def new_function(old_function):
        def another_newfunction(arg):
            if(isinstance(arg, correct_type)):
                return old_function(arg)
            else:
                print "Bad Type"
        return another_newfunction
    return new_function

EDIT : there was also some types, fixed by andrean

这篇关于在Python中使用装饰器进行类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆