Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过参数提示进行类型转换_Python_Python 3.x - Fatal编程技术网

Python 通过参数提示进行类型转换

Python 通过参数提示进行类型转换,python,python-3.x,Python,Python 3.x,给定一个带有\uuu str\uuuu()方法的自定义类,是否可以将这种类型的对象自动类型转换为函数的字符串参数,并且入侵最小?理想情况下使用类型提示,但也可以使用装饰器 例如,给定以下代码: class Custom: def __init__(self, name): self.name = name def __str__(self): return name def do_stuff(arg: str): return hash

给定一个带有
\uuu str\uuuu()方法的自定义类,是否可以将这种类型的对象自动类型转换为函数的字符串参数,并且入侵最小?理想情况下使用类型提示,但也可以使用装饰器

例如,给定以下代码:

class Custom:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return name

def do_stuff(arg: str):
    return hash(arg)

my_custom_var = Custom('my_name')
do_stuff(my_custom_var)

我想
do\u stuff
返回'my\u name'的哈希值。这可能吗?

据我所知,Python并没有真正隐式地转换类型,它只有在函数
hash
本身在某个点调用对象上的
str
时才会工作

您可以编写一个decorator,尝试将参数转换为
str
,但decorator只是一个函数包装器,它仍然需要直接调用它。

您可以在对象上使用。这会隐式调用
\uu str\uu()
方法,类似于print()


除非您自己对
\uuuuu注释\uuuuu
执行某些操作,否则类型提示不会产生任何运行时效果。如果这样做的唯一目的是使类可散列,那么只需实现一个
\uuuuuuuuuuuuuu
方法。
do_stuff(str(my_custom_var))