如何使函数从参数中调用,例如args.IsNullOrEmpty()而不是Python中的IsNullOrEmpty(args)

2024-10-02 16:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用从参数调用的函数

def IsNullOrEmpty(strInput):
    #strInput is string type (built-in)
    #doing something

上述函数的调用方式如下:

IsNullOrEmpty(strInput)

我怎样才能生成这样一个函数呢?而不使新类从内置的字符串类扩展

strInput.IsNullOrEmpty()

Tags: 函数in参数stringisdeftype方式
2条回答

下面是一个调整数据类型以接受外部属性的示例:

class unicode (__builtins__.unicode):
    def __new__ (cls, u=""):
        self = __builtins__.unicode.__new__(cls, u)
        return self

# So, you do it just once and then you can:
def add_check (obj):
    obj.IsNullOrEmpty = lambda: not obj

u1 = unicode("12345")
u2 = unicode()
add_check(u1)
add_check(u2)

print u1.IsNullOrEmpty()
print u2.IsNullOrEmpty()

注:使用:

u3 = u'1234'

将产生内置的.unicode(),而不是我们修改过的类型,因此您必须是显式的

您可以扩展Python内置类型,不过如果您不小心,可能会发现自己在处理一些奇怪的情况。例如:

class MyStr(str):
    def is_null_or_empty(self):  # see PEP 8 for naming conventions
        return not bool(self)

str1, str2 = MyStr("non-empty"), MyStr("")
print(str1.is_null_or_empty(), str2.is_null_or_empty())

应该打印

False True

请注意,所有从基类(系统str类型)继承并返回字符串的方法将继续返回简单字符串,而不是MyStr实例。要让它们返回这样的实例,类需要包装每个这样的方法。以下是upper方法的示例:

def upper(self):
    return MyStr(super().upper())

这里super().upper()是对超类(i,.e.)的调用strupper方法,其中self作为当前实例(因此作为参数1传递给该方法)-它不能再简单地从self继承和引用,因为upperMyStr定义将首先被解析,从而导致无限递归

相关问题 更多 >