为什么要运行这个类? [英] Why does this class run?

查看:52
本文介绍了为什么要运行这个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩我的代码一段时间,这不是一个错误或任何东西,但我只是不明白为什么 class main() 不需要初始化就运行......

I've been playing with my codes a little for a while, and this one is not about a bug or anything, but i just don't understand why class main() runs without needing to initialize it...

class vars():
    var1 = "Universe!"
    var2 = "Oscar!"
    var3 = "Rainbow!"

class main():
    print (vars.var1)
    def __init__(self):
        print (vars.var2)
        print (vars.var3)

是的,非常感谢您的阅读.

But yes, thank you very much for reading.

推荐答案

与许多其他语言不同,类主体是 Python 中的可执行语句,并在解释器到达 class 行时立即执行.当你运行这个程序"时:

Unlike many other languages, class body is an executable statement in Python and is executed immediately as the interpreter reaches the class line. When you run this "program":

class Foo:
    print("hey")

它只是打印hey"而没有创建任何 Foo 对象.

it just prints "hey" without any Foo object being created.

同样适用于函数定义语句def(但不适用于函数体).当你运行这个:

The same applies to the function definition statement def (but not to function bodies). When you run this:

def foo(arg=print("hi")):
    print("not yet")

它会打印hi",但不会打印not yet".

it prints "hi", but not "not yet".

这篇关于为什么要运行这个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆