为什么一个类被“称为"?什么时候不发起?- Python [英] Why does a class get "called" when not initiated? - Python

查看:35
本文介绍了为什么一个类被“称为"?什么时候不发起?- Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在以下代码中:

class test:
    print "Hi"

Python 会自动打印 'hi'.抱歉,如果这是一个明显的问题,但我不知道为什么 Python 会这样做,除非启动了测试"对象.* 我几个月前才开始一般的编程,Python 是我的第一语言,所以请原谅我.

Python would automatically print 'hi'. Sorry if this is an obvious question, but I can't find out why Python would do that unless a 'test' object was initiated. * I just started programming in general a few months ago and Python is my first language, so please spare some mercy on me.

推荐答案

您正在构建一个类;类的主体作为构建定义的函数执行.该函数"的本地命名空间形成了组成类的属性集.请参阅class 声明 文档.

You are building a class; the body of a class is executed as a function to build the definition. The local namespace of that 'function' forms the set of attributes that make up the class. See the class statement documentation.

类体中的方法不会被执行;就像函数定义一样,你需要先调用它们.但是如果你不先调用类体,你根本不知道这个类有什么方法.

Methods in the class body are not executed; like function definitions, you need to call them first. But if you didn't first call the class body, you don't know what methods the class has, at all.

同样,当你导入一个模块时,模块中的任何顶级代码都会被执行,以形成模块命名空间.如果你把 print "Hi" 放在一个模块中,它也会立即执行.

In the same way, any top-level code in a module is executed when you import a module, to form the module namespace. If you put print "Hi" in a module, it is also executed immediately.

这篇关于为什么一个类被“称为"?什么时候不发起?- Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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