簡體   English   中英

如何在 Python 中創建多行注釋?

[英]How do I create multiline comments in Python?

如何進行多行注釋? 大多數語言都有塊注釋符號,例如:

/*

*/

您可以使用三引號字符串。 當它們不是文檔字符串(類/函數/模塊中的第一件事)時,它們將被忽略。

'''
This is a multiline
comment.
'''

(確保適當縮進前導'''以避免IndentationError 。)

Guido van Rossum (Python 的創建者)在推特上將此作為“專業提示”。

然而,Python 的風格指南 PEP8傾向於使用連續的單行注釋,如下所示:

# This is a multiline
# comment.

...這也是您在許多項目中會發現的。 文本編輯器通常有一個快捷方式來輕松完成此操作。

Python 確實具有多行字符串/注釋語法,除非用作文檔字符串,否則多行字符串不會生成字節碼——就像#前置注釋一樣。 實際上,它的行為與評論完全一樣。

另一方面,如果您說這種行為必須在官方文檔中記錄為真正的注釋語法,那么是的,您可以說它不能作為語言規范的一部分得到保證。

在任何情況下,您的文本編輯器還應該能夠輕松地注釋掉選定的區域(通過在每行前面分別放置一個# )。 如果沒有,請切換到可以的文本編輯器。

在沒有某些文本編輯功能的情況下使用 Python 編程可能是一種痛苦的體驗。 找到合適的編輯器(並知道如何使用它)可以對 Python 編程體驗的感知方式產生很大影響。

文本編輯器不僅應該能夠注釋掉選定的區域,它還應該能夠輕松地左右移動代碼塊,並且當您按下Enter時,它應該自動將光標置於當前縮進級別。 代碼折疊也很有用。


為了防止鏈接衰減,這里是Guido van Rossum 的推文內容:

@BSUCSClub Python 提示:您可以使用多行字符串作為多行注釋。 除非用作文檔字符串,否則它們不會生成任何代碼! :-)

從接受的答案...

您可以使用三引號字符串。 當它們不是文檔字符串(類/函數/模塊中的第一件事)時,它們會被忽略。

這是不正確的。 與注釋不同,三引號字符串仍然會被解析並且必須在語法上有效,無論它們出現在源代碼中的什么位置。

如果您嘗試運行此代碼...

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

你會得到...

ValueError: invalid \x escape

...在 Python 2.x 或...

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

...在 Python 3.x 上。

執行解析器忽略的多行注釋的唯一方法是......

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()

在 Python 2.7 中,多行注釋是:

"""
This is a
multilline comment
"""

如果你在一個班級里,你應該正確地標記它。

例如:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """

AFAIK,Python 沒有塊注釋。 要注釋單個行,您可以使用#字符。

如果您使用的是Notepad++則有一個用於塊注釋的快捷方式 我相信像gVimEmacs這樣的其他人也有類似的功能。

我認為它沒有,除了不處理多行字符串。 但是,大多數(如果不是全部)Python IDE 都有一個用於“注釋掉”多行代碼的快捷鍵。

沒有像多行注釋這樣的功能。 #是注釋一行代碼的唯一方法。 你們中的許多人回答'''評論'''這是他們的解決方案。

它似乎有效,但在 Python 內部'''將包含的行作為常規字符串進行,解釋器不會像使用#的注釋一樣忽略這些行。

在此處查看官方文檔

如果你在里面發表評論

"""
long comment here
"""

在腳本中間,Python/linter 無法識別。 折疊會搞砸,因為上述評論不是標准建議的一部分。 最好用

# Long comment
# here.

如果你使用Vim ,你可以使用諸如commentary.vim之類的插件,通過按Vjgcc來自動注釋掉長行的注釋。 其中Vj選擇了兩行代碼, gcc將它們注釋掉。

如果您不想使用上述插件,可以使用搜索和替換

:.,.+1s/^/# /g

這將用#替換當前行和下一行的第一個字符。

Visual Studio Code通用官方多行注釋切換。 類似於 Xcode 快捷方式。

macOS:選擇代碼塊,然后 + /

Windows:選擇代碼塊,然后按 Ctrl + /

不幸的是,字符串化不能總是用作注釋掉! 因此,堅持在每行前面加上#的標准會更安全。

這是一個例子:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

我建議不要在多行注釋中使用"""

下面是一個簡單的示例,用於強調可能被視為意外行為的情況:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

現在看看輸出:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

多行字符串不被視為注釋,但它與'clearly I'm also a string'連接以形成單個字符串。

如果您想根據PEP 8指南評論多行

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

輸出:

I am a string
clearly I am also a string

好吧,你可以試試這個(運行引用時,第一個問題的輸入應該用'引用):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

"""之間的任何內容都將被注釋。

如果您正在尋找單行注釋,那么它是#

Python中的多行注釋:

對我來說,''' 和 """ 都有效。

例子:

a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)

例子:

a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)

在 Python 2.7.13 上:

單身的:

"A sample single line comment "

多行:

"""
A sample
multiline comment
on PyCharm
"""

Python 中的內聯注釋以哈希字符開頭。

hello = "Hello!" # This is an inline comment
print(hello)

你好!

請注意,字符串文字中的哈希字符只是一個哈希字符。

dial = "Dial #100 to make an emergency call."
print(dial)

撥打#100 撥打緊急電話。

哈希字符也可用於單行或多行注釋。

hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)

你好

世界

用三個雙引號將文本括起來以支持文檔字符串。

def say_hello(name):
    """
    This is docstring comment and
    it's support multi line.
    :param name it's your name
    :type name str
    """
    return "Hello " + name + '!'


print(say_hello("John"))

你好約翰!

用三個單引號將文本括起來以表示塊注釋。

'''
I don't care the parameters and
docstrings here.
'''

如果在一行代碼中寫注釋,必須寫注釋,#號前留2個空格,#號前留1個空格

print("Hello World")  # printing

如果在新行寫注釋,則必須寫注釋,在#號處留1個空格kn

# single line comment

要寫超過 1 行的評論,請使用 3 個引號

"""
This is a comment
written in
more than just one line
"""

使用 PyCharm IDE。

您可以使用Ctrl+/ commentuncomment代碼行。 Ctrl+/用單行注釋注釋或取消注釋當前行或選定的幾行({# in Django templates, or # in Python scripts) 在 Django 模板中為選定的源代碼塊Pressing Ctrl+Shift+/會用{% comment %} and {% endcomment %}標簽包圍該塊。


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

選擇所有行,然后按Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")

是的,兩者都可以使用:

'''
Comments
'''

"""
Comments
"""

但是,在 IDE 中運行時,您唯一需要記住的是,您必須“運行”整個文件才能被接受為多行代碼。 逐行“運行”將無法正常工作,並會顯示錯誤。

在其他答案中,我發現最簡單的方法是使用使用#的 Python 注釋支持的 IDE 注釋函數。

我正在使用 Anaconda Spyder,它具有:

  • Ctrl + 1 - 評論/取消評論
  • Ctrl + 4 - 注釋代碼塊
  • Ctrl + 5 - 取消注釋代碼塊

它會用#注釋/取消注釋單行/多行代碼。

我覺得是最簡單的。

例如,塊注釋:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

這可以在 Vim 文本編輯器中完成。

Go 到評論區第一行的開頭。

按 Ctrl+V 進入可視模式。

使用箭頭鍵 select 所有要注釋的行。

按 Shift+I。

按 #(或 Shift+3)。

按 Esc。

Python 中實際上並不存在多行注釋。 下面的示例包含一個未分配的字符串,由 Python 驗證語法錯誤。

一些文本編輯器,例如Notepad++ ,為我們提供了注釋一段書面代碼或文字的快捷方式。

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

此外, Ctrl + K是 Notepad++ 中阻止評論的快捷方式。 它在所選內容下的每一行前面添加一個# Ctrl + Shift + K用於塊取消注釋。

選擇要評論的行,然后使用Ctrl + ? Sublime Text編輯器中注釋或取消注釋 Python 代碼。

對於單行,您可以使用Shift + #

要在 Python 中注釋掉多行代碼,只需在每一行上使用#單行注釋:

# This is comment 1
# This is comment 2 
# This is comment 3

在 Python 中編寫“正確的”多行注釋是使用具有"""語法的多行字符串 Python 具有文檔字符串(或文檔字符串)功能。它為程序員提供了一種簡單的方法,可以為每個 Python 模塊添加快速注釋,函數、類和方法。

'''
This is
multiline
comment
'''

另外,提到您可以通過這樣的類對象訪問文檔字符串

myobj.__doc__

您可以使用以下內容。 這稱為 DockString。

def my_function(arg1):
    """
    Summary line.
    Extended description of function.
    Parameters:
    arg1 (int): Description of arg1
    Returns:
    int: Description of return value
    """
    return arg1

print my_function.__doc__

是的,您可以簡單地使用

'''
Multiline!
(?)
'''

或者

"""
Hello
World!
"""

獎勵:有點難,但在舊版本、 print功能或 GUI 中使用更安全:

# This is also
# a multiline comment.

對於這一點,您可以在PyCharmVS Code中選擇要評論的文本並按Ctrl / (或 / )。

但是您可以編輯它們。 例如,您可以將快捷方式從Ctrl /更改為Ctrl Shift C

警告!

  1. 小心,不要覆蓋其他快捷方式!
  2. 注釋必須正確縮進!

希望這個答案有所幫助。 祝你下次寫其他答案時好運!

在 windows:您也可以 select 文本或代碼塊,然后按ctr + /如果要刪除注釋,請執行相同操作。 在 mac 中:應該是comment + /

我閱讀了執行此操作的各種方法的所有缺點,並想出了這種方法,以嘗試檢查所有框:

block_comment_style = '#[]#'
'''#[
class ExampleEventSource():
    def __init__(self):
        # create the event object inside raising class
        self.on_thing_happening = Event()

    def doing_something(self):
        # raise the event inside the raising class
        self.on_thing_happening()        
        
        
class ExampleEventHandlingClass():
    def __init__(self):
        self.event_generating_thing = ExampleEventSource()
        # add event handler in consuming class
        event_generating_thing.on_thing_happening += my_event_handler
        
    def my_event_handler(self):
        print('handle the event')
]#'''


class Event():
 
    def __init__(self):
        self.__eventhandlers = []
 
    def __iadd__(self, handler):
        self.__eventhandlers.append(handler)
        return self
 
    def __isub__(self, handler):
        self.__eventhandlers.remove(handler)
        return self
 
    def __call__(self, *args, **keywargs):
        for eventhandler in self.__eventhandlers:
            eventhandler(*args, **keywargs)

優點

  1. 對於任何其他程序員來說,很明顯這是一條注釋。 這是自我描述的。
  2. 它編譯
  3. 它不會在help()中顯示為文檔注釋
  4. 如果需要,它可以位於模塊的頂部
  5. 它可以通過宏自動化。
  6. [評論]不是代碼的一部分。 它不會出現在pyc中。 (除了啟用優點#1和#4的一行代碼)
  7. 如果在 Python 中添加了多行注釋語法,則可以使用查找和替換來修復代碼文件。 簡單地使用'''沒有這個優勢。

缺點

  1. 很難記住。 打字很多。 這個騙局可以用宏來消除。
  2. 它可能會讓新手誤以為這是阻止評論的唯一方法。 那可能是專業人士,這取決於您的觀點。 它可能會讓新手認為代碼行神奇地連接到注釋“工作”。
  3. 它不會作為評論着色。 但是話又說回來,沒有一個真正解決OP問題精神的答案。
  4. 這不是官方的方式,所以Pylint可能會抱怨它。 我不知道。 也許; 也許不吧。

這是對 VS Code 宏的嘗試,雖然我還沒有測試過:

{
    "key": "ctrl+shift+/",
    "command": "editor.action.insertSnippet",
    "when": "editorHasSelection"
    "args": {
        "snippet": "block_comment_style = '#[]#'\n'''#[{TM_SELECTED_TEXT}]#'''"
    }
}

在python中,您可以按照以下步驟輕松使用多行注釋

您可以將此文檔字符串用於 Python 中的多行注釋。

""" print("結果為真")

"""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM