当前位置:首页>python>Python面向对象编程练习 1 LEGB规则(局部-嵌套-全局-内置规则)

Python面向对象编程练习 1 LEGB规则(局部-嵌套-全局-内置规则)

  • 2026-10-06 14:10:24
Python面向对象编程练习 1 LEGB规则(局部-嵌套-全局-内置规则)

练习1

定义了stock_info()函数。使用stock_info()函数的适当属性,在控制台显示该函数所有参数的名称。
函数调用示例:
print(stock_info('ABC', 'USA', 115, '$'))
输出:
Company: ABCCountry: USAPrice: $ 115
提示:使用函数的code属性。
预期结果:
('company', 'country', 'price', 'currency')
def stock_info(company, country, price, currency):    return f'Company: {company}\nCountry: {country}\nPrice: {currency}{price}'

练习2

使用内置模块导入sum()函数。然后显示该函数的文档。在以下列表上调用该函数并将结果打印到控制台。
[-4, 3, 2]
 预期结果: 
Help on built-in function sum in module builtins:sum(iterable, /, start=0)    Return the sum of a 'start' value (default: 0) plus an iterable of numbers    When the iterable is empty, return the start value.    This function is intended specifically for use with numeric values and may reject non-numeric types.1 
解决方案:
import builtinshelp(builtins.sum)print(builtins.sum([-4, 3, 2]))

练习3

给定一个全局变量counter和一个实现不正确的update_counter()函数。请更正update_counter()函数的实现,以便可以从此函数修改counter变量。然后调用update_counter()函数。
提示:使用global语句。
预期结果:
2
counter = 1def update_counter():    global counter    counter += 1    print(counter) 

练习4

给定以下全局变量:
  • counter
  • dot_counter
以及实现不正确的update_counters()函数。请更正update_counters()函数的实现,以便可以从此函数修改给定全局变量的值。然后调用update_counters() 40次。
作为响应,按如下所示将counter和dot_counter全局变量的值打印到控制台。
提示:使用global语句。
预期结果:
40........................................
counter = 0dot_counter = ''def update_counters():    global counter, dot_counter    counter += 1    dot_counter += '.'

练习5

实现了display_info()函数。该函数有一个实现不正确的内部update_counter()函数。请更正此函数的实现,以便可以从内部函数update_counter()修改非局部变量:counter和dot_counter。
作为响应,使用number_of_updates参数设置为10来调用display_info()。
提示:使用nonlocal语句。
预期结果:
110..........
def display_info(number_of_updates=1):    counter = 100    dot_counter = ''    def update_counter():        nonlocal counter, dot_counter        counter += 1        dot_counter += '.'    [update_counter() for _ in range(number_of_updates)]    print(counter)    print(dot_counter)

最新文章

随机文章