标签: isinstance

Python open的类型是什么(文件)

我想使用isinstance内置函数来判断的类型open(file)

怎么做?

谢谢!:D

python filehandle python-2.7 isinstance

0
推荐指数
2
解决办法
2936
查看次数

isinstance()方法python返回错误的值

list_d = ["a","b","c",3,5,4,"d","e","f",1,"ee"]
list_e = []

print("Before: %s"%(list_d))
print("Before: %s"%(list_e))

for item in list_d:
    if isinstance(item,int):
        list_d.pop(item)
        list_e.append(item)

print("After: %s"%(list_d))
print("After: %s"%(list_e))
Run Code Online (Sandbox Code Playgroud)

我有这个代码.我想将list_d中的这些数字传递给list_e,但结果是:

Before: ['a', 'b', 'c', 3, 5, 4, 'd', 'e', 'f', 1, 'ee']
Before: []
After: ['a', 'c', 5, 'd', 'e', 'f', 1, 'ee']
After: [3, 4, 1]
Run Code Online (Sandbox Code Playgroud)

不知何故5和1没有弹出,1附加到list_e但5不是.我的代码出了什么问题?

python isinstance

0
推荐指数
1
解决办法
57
查看次数

Python assert isinstance() 向量

我正在尝试在 python 中实现一个 Vector3 类。如果我用 c++ 或 c# 编写 Vector3 类,我会将 X、Y 和 Z 成员存储为浮点数,但在 python 中我读到ducktyping 是要走的路。所以根据我的 c++/c# 知识,我写了这样的东西:

class Vector3:
    def __init__(self, x=0.0, y=0.0, z=0.0):
        assert (isinstance(x, float) or isinstance(x, int)) and (isinstance(y, float) or isinstance(y, int)) and \
               (isinstance(z, float) or isinstance(z, int))
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)
Run Code Online (Sandbox Code Playgroud)

问题是关于断言语句:在这种情况下你会使用它们还是不使用它们(数学的 Vector3 实现)。我也用它来做类似的操作

def __add__(self, other):
    assert isinstance(other, Vector3)
    return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
Run Code Online (Sandbox Code Playgroud)

你会在这些情况下使用断言吗?根据这个网站:https : //wiki.python.org/moin/UsingAssertionsEffectively它不应该被过度使用,但对于我这个一直使用静态类型的人来说,不检查相同的数据类型是非常奇怪的。

python assert duck-typing isinstance

0
推荐指数
1
解决办法
2万
查看次数

是双重的

这可能是一个愚蠢的问题,但我在某处读到Python中的浮点数等于C++中的双精度数.因此,如果我想检查变量是否为double,我应该使用以下内容:

isinstance(v, float)
Run Code Online (Sandbox Code Playgroud)

或者这个:

isinstance(v, double)
Run Code Online (Sandbox Code Playgroud)

python floating-point isinstance

-3
推荐指数
1
解决办法
2171
查看次数