有这段代码:
#include <iostream>
class SomeClass
{
int someInteger;
float someFloat;
public:
SomeClass(int someInteger_)
{
// do something for int
std::cout << "Int constructor\n";
}
SomeClass(float someFloat_)
{
// do something for float
std::cout << "Float constructor\n";
}
};
int main()
{
SomeClass a(2);
SomeClass b(2.0f);
return 0;
}
当传递构造函数的float或int参数时,SomeClass类的对象会被不同地创建。 Python中有类似的类:
class SomeClass:
someInteger = 0
someFloat = 0.0
def __init__(self, value):
# I want to do different things when int or float is passed
print value
a = SomeClass(2)
b = SomeClass(2.0)
一般问题是 - 如何使函数行为依赖于传递参数的类型?
答案 0 :(得分:5)
使用isinstance
:
>>> isinstance(1, int)
True
>>> isinstance(1, float)
False
>>> isinstance(1.1, float)
True
>>> isinstance(1.1, int)
False
或者你的构造函数:
def __init__(self, value):
if isinstance(value, int):
# int constructor
elif isinstance(value, float):
# float constructor
else:
raise TypeError, 'Unexpected type'