简体   繁体   English

Python布尔方法命名约定

[英]Python boolean methods naming convention

I'm a Rubyist learning Python and I'm wondering if there is a convention in Python along the lines of the following. 我是Rubyist学习Python,我想知道Python中是否有一个约定如下。

In Ruby, methods that return booleans are supposed to always end in a ? 在Ruby中,返回布尔值的方法应该总是以? . For example, 例如,

def palindrome?(string)
  # some code that tests whether string is a palindrome
end

The only existing SO question I can find speaking to this does not provide a definitive answer. 我能找到的唯一现有的SO问题并没有提供明确的答案。

I concur with @CarolChen on the principle of turning to PEP8 , the Python Style Guide, for guidance. 我同意@CarolChen关于转向PEP8 (Python样式指南)的原则以获得指导。 I will suggest however that "as necessary to improve readability" is in the eye of the beholder. 然而,我会建议“视需要提高可读性”是旁观者的眼睛。 For example, each of these functions are used in Python either as functions of the str object or as builtin functions. 例如,这些函数中的每一个都在Python中用作str对象的函数或内置函数。 These are as fundamental as it gets in the Python ecosystem and are good examples of a usage style focused on returning a boolean state AND having easily readable function names. 这些都是Python生态系统中的基础,并且是一个使用样式的好例子,专注于返回布尔状态并具有易于读取的函数名称。

str. 海峡。 methods 方法

isalnum()
isalpha()
isdecimal()
isdigit()
isidentifier()
islower()
isnumeric()
isprintable()
isspace()
istitle()
isupper()

builtin functions: 内置功能:

isinstance()
issubclass()

There is no standard naming convention specific to boolean-returning methods. 没有特定于布尔返回方法的标准命名约定。 However, PEP8 does have a guide for naming functions. 但是,PEP8确实有命名功能的指南

Function names should be lowercase, with words separated by underscores as necessary to improve readability. 函数名称应为小写,并根据需要用下划线分隔,以提高可读性。

Typically, people start a function with is (eg is_palindrome ) to describe that a boolean value is returned. 通常,人们用is (例如is_palindrome )开始一个函数来描述返回一个布尔值。

You can define it like 你可以定义它

def is_palindrome(variable):
    # your logic\
    # return True / False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM