Python 如何检查变量';s型是原始的吗?
我不知道如何检查一个变量是否是原始变量。在Java中是这样的:Python 如何检查变量';s型是原始的吗?,python,Python,我不知道如何检查一个变量是否是原始变量。在Java中是这样的: if var.isPrimitive(): In [241]: get_builtins() Out[241]: ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildP
if var.isPrimitive():
如果有帮助的话In [241]: get_builtins() Out[241]: ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'display', 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
[1]中的In [1]: type(1) Out[1]: <type 'int'> In [2]: type('a') Out[2]: <type 'str'> In [3]: (type(5.4) Out[3]: <type 'float'> In [5]: type(object) Out[5]: <type 'type'> In [8]: type(int) Out[8]: <type 'type'>
:类型(1) 出[1]: 在[2]中:键入('a') 出[2]: 在[3]中:(类型(5.4) 出[3]: 在[5]中:类型(对象) 出[5]: In[8]:类型(int) 出[8]:
< /代码> 因为Python中没有基元类型,所以你自己必须定义你认为原始的:primitive = (int, str, bool, ...) def is_primitive(thing): return isinstance(thing, primitive)
但是,你也认为这个原语:
? 如果没有,您可以这样做:class MyStr(str): ...
def is_primitive(thing): return type(thing) in primitive
在Python中明确地说出什么是“原始”是不容易的,但是你可以做一个列表并检查你想要的:is_primitive = isinstance(myvar, (int, float, bool)) # extend the list to taste
您可能想看看模块,它列出了所有python内置类型类型
在Python中,任何东西都是对象;即使是int和bools。因此,如果“primitive”的意思是“not a object”(我认为Java中使用了这个词),那么Python中就没有这样的类型 如果您想知道给定的值(请记住,在Python中,变量没有类型,只有值有)是否是int、float、bool或任何您认为是“primitive”的类型,那么您可以执行以下操作:(我需要提到类型也是对象,有自己的类型吗?) 如果您还需要说明为内置类型创建子类的类型,请查看内置的isinstance()函数if type(myval) in (int, float, bool, str ...): # Sneaky stuff
Python大师尝试编写对将要发送的类型进行最小假设的代码。允许这是该语言的优势之一:它通常允许代码以意外的方式工作。因此,您可能希望避免编写任意区分类型的代码。正如每个人所说,在但是我相信,这就是你想要的这项工作:def isPrimitive(obj): return not hasattr(obj, '__dict__') isPrimitive(1) => True isPrimitive("sample") => True isPrimitive(213.1311) => True isPrimitive({}) => True isPrimitive([]) => True isPrimitive(()) => True class P: pass isPrimitive(P) => False isPrimitive(P()) => False def func(): pass isPrimitive(func) => False
Python 3.6:try: import builtins except ImportError: import __builtin__ as builtins def get_builtins(): return list(filter(lambda x: not x.startswith('_'), dir(builtins)))
Python中的“基元”类型是什么?:)(有些类型在CPython 2.x中表现得有点滑稽,因为它们是[本机]实现的,但没有“基元”类型的概念。)你说的“是基元”是什么意思?我认为Python不像Java那样具有原语。好吧,我猜如果它是bool、str或数字变量……字符串在Java中不是原语;-)无论如何,考虑更新特定的要求和/或用例的原始帖子。这很可能会得到(更好的)回复。。。为什么你认为<代码> STR 原始类型?在Java中,它是一个对象。在C语言中,它是一个字符数组(基本类型)。好吧,如果所有的东西都是一个对象,为什么我可以执行“1”。\uuuuEq\uEq(“2”)=>False,但不是1.\uEq\uEq(2)=>语法错误:无效语法?令人惊讶……这是因为一个数字可以包含一个点(例如,1.23只是一个数字,0.e2也是)。这会混淆解析器。如果你把数字用括号括起来,它就行了。(1) ._ueq_uu(2)=>假。然而,在Python中很少需要这样做,所以根据这个规则,类型和函数不是原始的?我相信OP有一种方法可以重新表述他/她的代码,这样就不需要对“基元”和“聚合”类型进行任意区分。我认为什么是基元,什么是标准类或内置函数存在一些混淆。原语是原语,它们很简单,表示一段数据,如。dict是用于存储对象(可写)属性的特殊属性。如果对象没有属性,则它是一个基本体。例如,如果您传递上述函数int或str:isPrimitive(int),它会说False,因为它确实具有dict属性。因此,即使是int、str或float等,类和函数也不被视为原语。。这段数据是一个基本数据,我相信这不会像@Mark所问的那样适用于使用的对象。有人能证实吗?这客观上很可怕。\uuuuuu插槽\uuuuuuuu
函数名在这里是一个明显的误称,保证会返回误报。不要在生产代码中这样做,伙计们。根据定义,此函数实际测试的是传递的对象是否是开槽的(即定义了isPrimitive()
类dunder变量),这反过来与传递的对象是否满足“primitive.”primitive的纯粹主观定义没有多大关系≠ 内置的<代码>\uuuu slots\uuu