different meanings of brackets in python

烈酒焚心 提交于 2019-11-26 15:36:08

问题


I am curious, what do the 3 different brackets mean in python programming? Not sure if i'm correct about this, but please correct me if i'm wrong.

[] - # Normally used for dictionaries, list items
() - # Used to identify params
{} - # I have no idea what this does... 

Or if these brackets can be used for other purposes, any advises are welcomed! Thanks!


回答1:


  • []: Used to define mutable data types - lists, list comprehensions and for indexing/lookup/slicing.
  • (): Define tuples, order of operations, generator expressions, function calls and other syntax.
  • {}: The two hash table types - dictionaries and sets.



回答2:


() parentheses are used for order of operations, or order of evaluation, and are referred to as tuples. [] brackets are used for lists. List contents can be changed, unlike tuple content. {} are used to define a dictionary in a "list" called a literal.




回答3:


In addition to Maltysen's answer and for future readers: you can define the [] and () operators in a class, by defining the class methods:

  • __call__(self[, args...]) for ()
  • __getitem__(self, key) for []

An example is numpy.mgrid[...]. In this way you can define it on your custom-made objects for any purpose you like.



来源:https://stackoverflow.com/questions/30700603/different-meanings-of-brackets-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!