Python中全局变量的替代方案

huangapple go评论82阅读模式
英文:

Python alternative for global variable

问题

我正在尝试编写一个程序它接收一个名为source code的文本文件并逐行检查其中是否有两行以上的空行在代码行之前我认为只包含空白字符的行是空行

我的解决方案是使用全局变量作为前导空行的计数器

```python
import os
import re

blank_lines_counter = 0

def check_blank_lines(line):
    global blank_lines_counter

    if re.match('^\s*$', line):
        blank_lines_counter += 1
    else:
        if blank_lines_counter > 2:
            blank_lines_counter = 0
            return True
        blank_lines_counter = 0
    return False

with open('input_file.py', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    
    for i, line in enumerate(lines, 1):
        if check_blank_lines(line):
            print(f'第 {i} 行:在此行之前使用了两行以上的空行')

但我不喜欢它因为使用了全局变量。是否有任何方法可以以更高级的方式重写此代码,而不使用全局变量,但仍保持过程化编程范式(非面向对象编程)?


<details>
<summary>英文:</summary>

I am trying to write a program, that takes &quot;source code&quot; text file, and checks it line-by-line for more than two blank lines preceding a code line. I consider that line containing only whitespaces is blank.

My solution is to use global variable as a counter for preceding blank lines:


import os
import re

blank_lines_counter = 0

def check_blank_lines(line):
global blank_lines_counter

if re.match(&#39;^\s*$&#39;, line):
    blank_lines_counter += 1
else:
    if blank_lines_counter &gt; 2:
        blank_lines_counter = 0
        return True
    blank_lines_counter = 0
return False

with open('input_file.py', 'r', encoding='utf-8') as f:
lines = f.readlines()

for i, line in enumerate(lines, 1):
    if check_blank_lines(line):
        print(f&#39;Line {i}: More than two blank lines used before this line&#39;)


But I don&#39;t like it because of global variable. Is there any way to rewrite this code in more fancy way and not using global variables, but still in procedural programming paradigm (not OOP)?

</details>


# 答案1
**得分**: 3

我强烈建议在Python中学习/使用面向对象编程(它非常有用!)

如果你不想这样做,你可以通过将`blank_lines_counter`作为函数参数传递来消除使用全局关键字,它会看起来像这样:

```python
def check_blank_lines(line: str, blank_lines_counter: int):
   [...]
   blank_lines_counter += 1
   return True, blank_lines_counter 
[...]

line_is_blank, blank_lines_counter = check_blank_lines(line, blank_lines_counter)
if line_is_blank:
    print(f'Line {i}: More than two blank lines used before this line')

省略号用于简洁起见。

英文:

I would heavily suggest learning/using OOP in python (It's super useful!)
If you don't want to however, you could remove the use of the global keyword by passing the blank_lines_counter as a function parameter instead, it would look something like that:

def check_blank_lines(line: str, blank_lines_counter: int):
   [...]
   blank_lines_counter += 1
   return True, blank_lines_counter 
[...]

line_is_blank, blank_lines_counter = check_blank_lines(line, blank_lines_counter)
if line_is_blank:
    print(f&#39;Line {i}: More than two blank lines used before this line&#39;)

Ellipses for brevity

答案2

得分: 2

你可以将它作为一个参数传递给函数。

例如,

def check_blank_lines(line, counter):
    ...
    return True, counter

counter = 0
for i, line in enumerate(lines, 1):
    is_blank, counter = check_blank_lines(line, counter)
    if is_blank:
        ...
英文:

You can pass it as a parameter to function.

Like,

def check_blank_lines(line, counter):
    ...
    return True, counter

counter = 0
for i, line in enumerate(lines, 1):
    is_blank, counter = check_blank_lines(line, counter)
    if is_blank:
        ...

huangapple
  • 本文由 发表于 2023年7月27日 23:30:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76781327.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定