Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在工作世界里什么';结构函数的全球标准是什么?_Python_Python 3.x_Methods_Pycharm - Fatal编程技术网

Python 在工作世界里什么';结构函数的全球标准是什么?

Python 在工作世界里什么';结构函数的全球标准是什么?,python,python-3.x,methods,pycharm,Python,Python 3.x,Methods,Pycharm,另一位用户告诉我,这是构造函数的更正确的方法: 显示用户信息(姓名、年龄和地址)的程序。 与之相比: def details(): print(f"{user_name} is {user_age} and lives at {user_address}.") user_age, user_name, user_address = int(input("Enter age: ")), input("Enter name: "

另一位用户告诉我,这是构造函数的更正确的方法:

显示用户信息(姓名、年龄和地址)的程序。 与之相比:

def details():
    print(f"{user_name} is {user_age} and lives at {user_address}.")


user_age, user_name, user_address = int(input("Enter age: ")), input("Enter name: "), input("Address: ")

details()
代码是动态的吗?每个项目是否有结构变化?或者上述代码仅仅是函数的总体布局/模板吗?

在您的两个代码示例中,两个重要的“东西”是不同的

  • 全局变量用法
  • 重要性
  • (1) 在函数中使用全局变量几乎总是一个坏主意。函数应将它们将要使用的所有外部数据作为参数,并返回它们生成的所有数据:

    # bad
    foo = 42
    def add1():
        global foo
        foo += 1
    
    # better
    foo = 42
    def add1(n):
        return n + 1
    foo = add1(foo)
    
    (2) 在全局范围内(函数外部)执行代码将使该代码在您将文件导入另一个模块时运行。您通常希望控制代码的执行时间,因此始终将代码放入函数中。然后,在运行一个文件时,使用
    if uuuuuuu name_uuuu==“\uuuuuuu main\uuuu:
    块执行代码:

    # bad
    foo = 42
    def add1(n):
        return n + 1
    foo = add1(foo)
    
    # better
    FOO = 42   # global variables should be all upper case by convention
    
    def add1(n):
        return n + 1
    
    if __name__ == "__main__":
        FOO = add1(FOO)
    

    关于你的程序的结构,你所问或谈论的并不清楚。你会问,“或者上面的代码仅仅是方法的默认布局结构吗?”但你所说的是什么布局结构?我指的是一般方法布局。你的确切意思是什么?说“一般方法布局”“没有告诉我关于你正在谈论的内容的其他信息。”另一位用户告诉我,与代码中甚至没有方法相比,这是构造方法的更正确的方法。
    # bad
    foo = 42
    def add1(n):
        return n + 1
    foo = add1(foo)
    
    # better
    FOO = 42   # global variables should be all upper case by convention
    
    def add1(n):
        return n + 1
    
    if __name__ == "__main__":
        FOO = add1(FOO)