如何实现未知类型变量间的类型转换及代码错误修正?
Convert a Variable to Another's Unknown Type (No Conditional Chains Needed)
Got it, let's figure out how to convert one variable to match the type of another when we don't know either type ahead of time, without using clunky switch statements or long if/elif lists.
The Fix for the Constructor Mistake
First, let's clear up the error in the original code: using type(y).__name__(x) throws a TypeError because __name__ returns a string (like "str"), which isn't a callable constructor. Instead, we need to use the actual type object from type(y) directly.
Here's the corrected working function:
def myfunc(x, y): if type(x) == type(y): print(x + y) else: # Convert x to y's type using the type's constructor x = type(y)(x) print(x + y)
Let's Test It with Your Example
Suppose x is an integer (42) and y is a string ("15"):
- Since
type(x)(int) doesn't matchtype(y)(str), we convertxto a string usingstr(42)which becomes"42". - Then we add them together:
"42" + "15"gives"4215", which gets printed.
If we reverse it—x is "7" and y is 3—it converts x to an integer (7) and adds to get 10.
Why This Approach Is Great
- It's dynamic: works for any built-in type (int, str, float, etc.) as long as the conversion is supported by the target type's constructor.
- No need for hardcoded conditionals: you don't have to list every possible type combination, which keeps the code clean and scalable.
内容的提问来源于stack exchange,提问作者mohammad syed
相关产品推荐
相关产品推荐

