Python 有哪些重要的语言特性(习语)需要尽早学习

发布于 2024-07-14 02:20:13 字数 497 浏览 8 评论 0原文

我有兴趣了解 StackOverflow 社区认为 Python 的重要语言特性(习语)是什么。 将程序员定义为 Pythonic 的特征。

Python (pythonic) 习语 - Python 语言自然的或特有的“代码表达式”。

另外,所有 Python 程序员都应该尽早学习哪些习惯用法?

提前致谢

相关:

I would be interested in knowing what the StackOverflow community thinks are the important language features (idioms) of Python. Features that would define a programmer as Pythonic.

Python (pythonic) idiom - "code expression" that is natural or characteristic to the language Python.

Plus, Which idioms should all Python programmers learn early on?

Thanks in advance

Related:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

不再见 2024-07-21 02:20:13

Python 是一种语言,可以描述为:

“您可以适应的规则
你的手掌上有一个巨大的袋子
钩子”。

遵循相同的简单标准。一切都是可访问的、可更改的和可调整的。语言级别的元素非常少。

以 len(data) 内置函数为例。len(data)< /code> 的工作原理是简单地检查 data.__len__() 方法,然后调用它并返回值,这样,len() 就可以对任何对象起作用。 ”


首先学习类型和基本语法:

  1. 动态强类型语言
  2. bool、int、float、string、list、tuple、dict、set
  3. 语句、缩进、“一切 是一个对象”
  4. 基本函数定义

然后继续学习 python 的工作原理:

  1. 导入和模块(非常简单)
  2. python 路径 (sys.path)
  3. dir() 函数
  4. __builtins____len__ 这样的

一旦您了解了如何将各个部分组合在一起,请返回并涵盖一些更高级的语言功能:

  1. 迭代器
  2. 重写(有很多这样的)
  3. 列表推导式和生成器
  4. 类和对象(同样,一旦您了解了一些规则,就非常简单)
  5. Python继承规则

一旦您对这些项目有了一定程度的了解(重点关注使它们变得Python化的原因),请查看更具体的项目:

  1. Python中的线程(请注意全局解释器锁)
  2. 上下文管理器
  3. 数据库访问
  4. 文件IO
  5. 套接字
  6. 等......

并且永远不要忘记Python的禅宗(作者:Tim Peters)

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Python is a language that can be described as:

"rules you can fit in the
palm of your hand with a huge bag of
hooks".

Nearly everything in python follows the same simple standards. Everything is accessible, changeable, and tweakable. There are very few language level elements.

Take for example, the len(data) builtin function. len(data) works by simply checking for a data.__len__() method, and then calls it and returns the value. That way, len() can work on any object that implements a __len__() method.


Start by learning about the types and basic syntax:

  1. Dynamic Strongly Typed Languages
  2. bool, int, float, string, list, tuple, dict, set
  3. statements, indenting, "everything is an object"
  4. basic function definitions

Then move on to learning about how python works:

  1. imports and modules (really simple)
  2. the python path (sys.path)
  3. the dir() function
  4. __builtins__

Once you have an understanding of how to fit pieces together, go back and cover some of the more advanced language features:

  1. iterators
  2. overrides like __len__ (there are tons of these)
  3. list comprehensions and generators
  4. classes and objects (again, really simple once you know a couple rules)
  5. python inheritance rules

And once you have a comfort level with these items (with a focus on what makes them pythonic), look at more specific items:

  1. Threading in python (note the Global Interpreter Lock)
  2. context managers
  3. database access
  4. file IO
  5. sockets
  6. etc...

And never forget The Zen of Python (by Tim Peters)

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
物价感观 2024-07-21 02:20:13

本页涵盖了所有主要的 python 习惯用法: http://python.net /~goodger/projects/pycon/2007/idiomatic/handout.html

This page covers all the major python idioms: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

旧情勿念 2024-07-21 02:20:13

Python 中的一个重要习惯用法是文档字符串。

每个对象都有一个 __doc__ 属性,可用于获取有关该对象的帮助。 您可以在模块、类、方法和函数上设置 __doc__ 属性,如下所示:

# this is m.py
""" module docstring """

class c:
    """class docstring"""
    def m(self):
        """method docstring"""
        pass

def f(a):
    """function f docstring"""
    return

现在,当您输入 help(m)help(mf) 等时,它会将文档字符串打印为帮助消息。

因为它只是正常对象内省的一部分,所以它可以由 epydoc 等文档生成系统使用,或者由 unittest 用于测试目的。

它还可以用于更非常规(即非惯用)的用途,例如 Dparser

对我来说更有趣的是,尽管 doc 在大多数对象上是只读属性,但您可以在任何地方使用它们,如下所示:

x = 5
""" pseudo docstring for x """

以及文档工具,例如 epydoc 可以拾取它们并正确格式化它们(而不是保留在代码格式中的普通注释。

An important idiom in Python is docstrings.

Every object has a __doc__ attribute that can be used to get help on that object. You can set the __doc__ attribute on modules, classes, methods, and functions like this:

# this is m.py
""" module docstring """

class c:
    """class docstring"""
    def m(self):
        """method docstring"""
        pass

def f(a):
    """function f docstring"""
    return

Now, when you type help(m), help(m.f) etc. it will print the docstring as a help message.

Because it's just part of normal object introspection this can be used by documention generating systems like epydoc or used for testing purposes by unittest.

It can also be put to more unconventional (i.e. non-idiomatic) uses such as grammars in Dparser.

Where it gets even more interesting to me is that, even though doc is a read-only attribute on most objects, you can use them anywhere like this:

x = 5
""" pseudo docstring for x """

and documentation tools like epydoc can pick them up and format them properly (as opposed to a normal comment which stays inside the code formatting.

孤者何惧 2024-07-21 02:20:13

装饰者得到我的投票。 您还可以在哪里编写类似以下内容

def trace(num_args=0):
  def wrapper(func):
    def new_f(*a,**k):
      print_args = ''
      if num_args > 0:
        print_args = str.join(',', [str(x) for x in a[0:num_args]])
      print('entering %s(%s)' %(f.__name__,print_args))
      rc = f(*a,**k)
      if rc is not None:
        print('exiting %s(%s)=%s' %(f.__name__,str(rc)))
      else:
        print('exiting %s(%s)' %(f.__name__))
      return rc
    return new_f
  return wrapper

@trace(1)
def factorial(n):
  if n < 2:
    return 1
  return n * factorial(n-1)
factorial(5)

并获得如下输出:

entering factorial(5)
entering factorial(4)
entering factorial(3)
entering factorial(2)
entering factorial(1)
entering factorial(0)
exiting factorial(0)=1
exiting factorial(1)=1
exiting factorial(2)=2
exiting factorial(3)=6
exiting factorial(4)=24
exiting factorial(5)=120

Decorators get my vote. Where else can you write something like:

def trace(num_args=0):
  def wrapper(func):
    def new_f(*a,**k):
      print_args = ''
      if num_args > 0:
        print_args = str.join(',', [str(x) for x in a[0:num_args]])
      print('entering %s(%s)' %(f.__name__,print_args))
      rc = f(*a,**k)
      if rc is not None:
        print('exiting %s(%s)=%s' %(f.__name__,str(rc)))
      else:
        print('exiting %s(%s)' %(f.__name__))
      return rc
    return new_f
  return wrapper

@trace(1)
def factorial(n):
  if n < 2:
    return 1
  return n * factorial(n-1)
factorial(5)

and get output like:

entering factorial(5)
entering factorial(4)
entering factorial(3)
entering factorial(2)
entering factorial(1)
entering factorial(0)
exiting factorial(0)=1
exiting factorial(1)=1
exiting factorial(2)=2
exiting factorial(3)=6
exiting factorial(4)=24
exiting factorial(5)=120
氛圍 2024-07-21 02:20:13

一切都与列表使用相关。
推导式、生成器等

Everything connected to list usage.
Comprehensions, generators, etc.

铜锣湾横着走 2024-07-21 02:20:13

就我个人而言,我真的很喜欢使用缩进来定义代码块的 Python 语法,而不是使用“BEGIN”和“END”一词(如 Microsoft 的 Basic 和 Visual Basic - 我不喜欢这些)或通过使用左大括号和右大括号(如 C、C++、Java、Perl - 我喜欢这些)。

这真的让我感到惊讶,因为虽然缩进对我来说一直非常重要,但我并没有对此发出太大的“噪音”——我忍受着它,并且它被认为是一种能够阅读其他人的技能,“意大利面条” “ 代码。 此外,我从未听到其他程序员建议将缩进作为语言的一部分。 直到Python! 我只希望我首先意识到这个想法。

对我来说,Python 的语法就好像迫使你编写良好的、可读的代码。

好吧,我会离开我的肥皂盒。 ;-)

Personally, I really like Python syntax defining code blocks by using indentation, and not by the words "BEGIN" and "END" (as in Microsoft's Basic and Visual Basic - I don't like these) or by using left- and right-braces (as in C, C++, Java, Perl - I like these).

This really surprised me because, although indentation has always been very important to me, I didn't make to much "noise" about it - I lived with it, and it is considered a skill to be able to read other peoples, "spaghetti" code. Furthermore, I never heard another programmer suggest making indentation a part of a language. Until Python! I only wish I had realized this idea first.

To me, it is as if Python's syntax forces you to write good, readable code.

Okay, I'll get off my soap-box. ;-)

怎言笑 2024-07-21 02:20:13

从更高级的角度来看,了解 Python 内部如何使用字典。 类、函数、模块、引用都只是字典上的属性。 一旦理解了这一点,就很容易理解如何进行猴子修补和使用强大的 __gettattr__、__setattr__ 和 __call__ 方法。

From a more advanced viewpoint, understanding how dictionaries are used internally by Python. Classes, functions, modules, references are all just properties on a dictionary. Once this is understood it's easy to understand how to monkey patch and use the powerful __gettattr__, __setattr__, and __call__ methods.

凉宸 2024-07-21 02:20:13

这是一个可以提供帮助的。 有什么区别

[ foo(x) for x in range(0, 5) ][0]

:和

( foo(x) for x in range(0, 5) ).next()

答案:
在第二个示例中, foo 仅被调用一次。 如果 foo 有副作用,或者用于构造列表的可迭代对象很大,那么这可能很重要。

Here's one that can help. What's the difference between:

[ foo(x) for x in range(0, 5) ][0]

and

( foo(x) for x in range(0, 5) ).next()

answer:
in the second example, foo is called only once. This may be important if foo has a side effect, or if the iterable being used to construct the list is large.

浸婚纱 2024-07-21 02:20:13

有两件事特别让我印象深刻,那就是动态类型和 Python 中使用的各种类型的列表,尤其是元组。

Python 对列表的痴迷可以说是 LISP-y,但它有自己独特的风格。 像这样的一行:

return HandEvaluator.StraightFlush, (PokerCard.longFaces[index + 4], 
  PokerCard.longSuits[flushSuit]), []

甚至

return False, False, False

只是看起来像 Python 而没有其他东西。 (从技术上讲,你也会在 Lua 中看到后者,但 Lua 总体来说非常 Pythonic。)

Two things that struck me as especially Pythonic were dynamic typing and the various flavors of lists used in Python, particularly tuples.

Python's list obsession could be said to be LISP-y, but it's got its own unique flavor. A line like:

return HandEvaluator.StraightFlush, (PokerCard.longFaces[index + 4], 
  PokerCard.longSuits[flushSuit]), []

or even

return False, False, False

just looks like Python and nothing else. (Technically, you'd see the latter in Lua as well, but Lua is pretty Pythonic in general.)

始终不够 2024-07-21 02:20:13

使用字符串替换:

name = "Joe"
age = 12
print "My name is %s, I am %s" % (name, age)

当我不使用 python 编程时,这种简单的使用是我最怀念的。

Using string substitutions:

name = "Joe"
age = 12
print "My name is %s, I am %s" % (name, age)

When I'm not programming in python, that simple use is what I miss most.

泅人 2024-07-21 02:20:13

另一件你不能尽早开始的事情可能是测试。 在这里,文档测试尤其是通过同时解释代码来测试代码的好方法。

doctests 是简单的文本文件,包含交互式解释器会话以及如下文本:

Let's instantiate our class::

>>> a=Something(text="yes")
>>> a.text
yes

Now call this method and check the results::

>>> a.canify()
>>> a.text
yes, I can

如果 egatext 返回不同的内容,则测试将失败。

doctests 可以位于文档字符串或独立文本文件中,并使用 doctests 模块 执行。 当然,也可以使用更知名的单元测试。

Another thing you cannot start early enough is probably testing. Here especially doctests are a great way of testing your code by explaining it at the same time.

doctests are simple text file containing an interactive interpreter session plus text like this:

Let's instantiate our class::

>>> a=Something(text="yes")
>>> a.text
yes

Now call this method and check the results::

>>> a.canify()
>>> a.text
yes, I can

If e.g. a.text returns something different the test will fail.

doctests can be inside docstrings or standalone textfiles and are executed by using the doctests module. Of course the more known unit tests are also available.

日记撕了你也走了 2024-07-21 02:20:13

我认为网上的教程和书籍只讲做事,而不是以最好的方式做事。 除了 python 语法之外,我认为在某些情况下速度也很重要。

Python 提供了一种对函数进行基准测试的方法,实际上是两种!!

一种方法是使用 profile 模块,如下所示:

import profile

def foo(x, y, z):
    return x**y % z # Just an example.

profile.run('foo(5, 6, 3)')

另一种方法是使用 timeit 模块,如下所示:

import timeit

def foo(x, y, z):
    return x**y % z # Can also be 'pow(x, y, z)' which is way faster.

timeit.timeit('foo(5, 6, 3)', 'from __main__ import *', number = 100) 
# timeit.timeit(testcode, setupcode, number = number_of_iterations)

I think that tutorials online and books only talk about doing things, not doing things in the best way. Along with the python syntax i think that speed in some cases is important.

Python provides a way to benchmark functions, actually two!!

One way is to use the profile module, like so:

import profile

def foo(x, y, z):
    return x**y % z # Just an example.

profile.run('foo(5, 6, 3)')

Another way to do this is to use the timeit module, like this:

import timeit

def foo(x, y, z):
    return x**y % z # Can also be 'pow(x, y, z)' which is way faster.

timeit.timeit('foo(5, 6, 3)', 'from __main__ import *', number = 100) 
# timeit.timeit(testcode, setupcode, number = number_of_iterations)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文