首页 > 解决方案 > 函数名和类名相同。编译器是如何工作的?如何或为什么?

问题描述

如果调用类,为什么构造函数不打印语句。如果没有调用类,那么为什么该打印语句有效?两次我们调用外部但只有一次打印功能有效?

例子.py

class outer:
    print("print")
    def __init__(self, h):
        print("Constructor ",h)

def outer(msg):
    print(msg)

outer("hello")
outer("hello")

输出 :

print
hello
hello

标签: pythonpython-3.x

解决方案


这里有两个不同的范围 - 使用模块范围而不是类范围的类似代码:

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 

推荐阅读