繁体   English   中英

python 中的对象类型对话

[英]Type conversation of objects in python

如何在 python 上编写一个 function 接受输入中的两个对象并在 output 上给出两个对象都可以呈现的最小类型? 例如,如果我们有[1, 2, 3]2我们可以将其转换为str ,如果我们有"Hi"1.2我们可以将其转换为str ,如果我们有True1.2我们可以将其转换为float和很快。

Python 中的所有对象都可以转换为字符串,甚至是用户定义的 class 实例。

>>> class Test:
    pass

>>> t = Test()
>>> str(t)
'<__main__.Test object at 0x0000015315891730>'
>>> str(1)
'1'
>>> str(True)
'True'
>>> str([1, 2, 3])
'[1, 2, 3]'
>>> 

这是因为他们有一个自动定义的__str__ function,即使你没有定义它。

编辑:你可以这样做(原谅丑陋的代码)

def leastConversions(first, second):
    type_casts = [str, int, float, tuple, list, dict]
    times = {}
    for _type in type_casts:

        if not isinstance(first, _type):
            times[_type] = 0
            try:
                if not isinstance(first, _type):
                    temp = _type(first)
                    times[_type] += 1
            except TypeError:
                del times[_type]
                continue
            
            try:
                if not isinstance(second, _type):
                    temp = _type(second)
                    times[_type] += 1
            except TypeError:
                del times[_type]
                continue
    return min(times, key = lambda k: times[k])
def type_convertion(first, second):
    data_types = [int, float, tuple, list, str]
    times = {}
    for _type in data_types:
        times[_type] = 0
        try:
            if isinstance(_type(first), _type):
                times[_type] += 1
        except TypeError:
            del times[_type]
            continue
        try:
            if isinstance(_type(second), _type):
                times[_type] += 1
        except TypeError:
            del times[_type]
            continue
        return times.keys()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM