python - 函数名和类名相同。编译器是如何工作的?如何或为什么?
问题描述
如果调用类,为什么构造函数不打印语句。如果没有调用类,那么为什么该打印语句有效?两次我们调用外部但只有一次打印功能有效?
例子.py
class outer:
print("print")
def __init__(self, h):
print("Constructor ",h)
def outer(msg):
print(msg)
outer("hello")
outer("hello")
输出 :
print
hello
hello
解决方案
这里有两个不同的范围 - 使用模块范围而不是类范围的类似代码:
print("initialization print")
def outer(msg):
print("message", msg)
def outer(msg):
print("message #2", msg)
outer("hello")
outer("hello")
将产生:
initialization print
message 2 hello
message 2 hello
要学习的关键是,缩进的所有内容都class
在类的定义时间内执行,而缩进的所有内容都def __init__(self)
发生在实例的定义时间:
class Example:
print("Defining what it means to be an Example")
def __init__(self, name):
print("Creating an instance of Example with the name ", name)
print("Example class created - no instances yet")
Example("Joe")
将产生:
Defining what it means to be an Example
Example class created - no instances yet
Creating an instance of Example with the name Joe
第二点是您在使用函数创建类后覆盖了类的绑定。outer
如果我们在 Python 中有匿名类和函数,您可以将它们视为赋值:
x = 1
x = 2
就像:
outer = class:
print("Creating class outer")
# ... etc. ...
outer = def(msg):
# you get the idea
推荐阅读
- mysql - MySQL 查询返回不同的结果
- excel - VBA中的Linest函数
- c# - BFS 和 DFS 使用邻接矩阵 C#
- r - 求解 R 中餐厅顾客类型的百分比
- r - 如果发生某些情况,请更改图表上的数字
- c# - 在 EF 中更新父表时无法更新子表
- python - (热编码目标变量)发现样本数量不一致的输入变量
- visual-studio-2019 - Visual Studio 2019 中的目标名称和输出文件有什么区别
- cocoapods - 如何在 iOS WidgetKit 中嵌入 Mapbox
- angular - 为什么在 Application Shell 中托管 MFE 远程应用程序时 DOM 不更新?