我正在学习Python,并希望从print语句的显示中识别数据结构。 我写了以下代码:
set1={1,2,3,3} print set1 tup1=(1,2,3,3) print tup1 list1=[1,2,3,3] print list1 dict1={1:1,2:2,3:3,3:3} print dict1输出是:
set([1, 2, 3]) (1, 2, 3, 3) [1, 2, 3, 3] {1: 1, 2: 2, 3: 3}从这里我推断set1是一个python集,tup1是一个python元组,list1是一个python列表,dict1是一个python字典。
我们能否以通用方式使用此类比来从print语句中识别基础数据结构?
I am learning Python and wanted to identify the data structure from the display of print statement. I wrote the following code:
set1={1,2,3,3} print set1 tup1=(1,2,3,3) print tup1 list1=[1,2,3,3] print list1 dict1={1:1,2:2,3:3,3:3} print dict1And the output is:
set([1, 2, 3]) (1, 2, 3, 3) [1, 2, 3, 3] {1: 1, 2: 2, 3: 3}From this I infer that set1 is a python set, tup1 is a python tuple, list1 is a python list and dict1 is a python dictionary.
Can we use this analogy in a generalized way to identify the underlying data structure from the print statement?
最满意答案
您正在查看repr()函数的输出。 它取决于对象本身提供有意义的object.__repr__()方法 ; 内置类型产生有效的Python语法,可以让你重现相同的值,但对于Python类, repr()输出并不总是有用:
>>> class Foo(object): ... def __init__(self, bar): ... self.bar = bar ... >>> print Foo(42) <__main__.Foo object at 0x102312990>这只会告诉您具有哪种类型的实例,而不是如何重现相同的值。
如果您只想知道类型 ,请使用type()函数 :
>>> type(Foo(42)) <class '__main__.Foo'> >>> type({1, 2, 3}) <type 'set'>You are looking at the output of the repr() function. It is up to the object itself to provide a meaningful object.__repr__() method; the built-in types produce valid Python syntax that'll let you reproduce the same value, but for Python classes the repr() output is not always as helpful:
>>> class Foo(object): ... def __init__(self, bar): ... self.bar = bar ... >>> print Foo(42) <__main__.Foo object at 0x102312990>This only tells you what type of instance you have, not how reproduce the same value.
If all you want to know is the type, use the type() function:
>>> type(Foo(42)) <class '__main__.Foo'> >>> type({1, 2, 3}) <type 'set'>更多推荐
发布评论