这两个代码片段之间有什么区别?使用type():
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
Run Code Online (Sandbox Code Playgroud)
使用isinstance():
if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个函数,将多个变量与一个整数进行比较,并输出一个由三个字母组成的字符串.我想知道是否有办法将其翻译成Python.所以说:
x = 0
y = 1
z = 3
mylist = []
if x or y or z == 0 :
mylist.append("c")
if x or y or z == 1 :
mylist.append("d")
if x or y or z == 2 :
mylist.append("e")
if x or y or z == 3 :
mylist.append("f")
Run Code Online (Sandbox Code Playgroud)
这将返回一个列表
["c", "d", "f"]
Run Code Online (Sandbox Code Playgroud)
这样的事情可能吗?
基本上我想这样做:
obj = 'str'
type ( obj ) == string
Run Code Online (Sandbox Code Playgroud)
我试过了:
type ( obj ) == type ( string )
Run Code Online (Sandbox Code Playgroud)
它不起作用.
另外,其他类型呢?例如,我无法复制NoneType.
我怎么做pythonicly:
var = 7.0
var_is_good = isinstance(var, classinfo1) or isinstance(var, classinfo2) or isinstance(var, classinfo3) or ... or isinstance(var, classinfoN)
Run Code Online (Sandbox Code Playgroud)
看起来很傻我不能只传入classinfo的列表:
var_is_good = isinstanceofany( var, [classinfo1, classinfo2, ... , classinfoN] )
Run Code Online (Sandbox Code Playgroud)
那么isinstanceofany功能是什么?
嗨,这是一段代码,应该创建一个函数,返回输入的整数或浮点数的绝对值.似乎无法弄清楚它有什么问题,这里是代码和错误.任何帮助表示赞赏!
这是函数的代码:
import math
def distance_from_zero(num):
type_entry = type(num)
if type_entry == int:
return math.abs(num)
elif type_entry == float:
return math.abs(num)
else:
return "Not an integer or float!"
Run Code Online (Sandbox Code Playgroud)
这是我通过打印结果测试代码的地方
print distance_from_zero(4)
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
File "python", line 12, in <module>
File "python", line 5, in distance_from_zero
AttributeError: 'module' object has no attribute 'abs'
Run Code Online (Sandbox Code Playgroud) python ×5
types ×3
compare ×1
comparison ×1
if-statement ×1
inheritance ×1
isinstance ×1
match ×1
oop ×1