gpt4 book ai didi

python - 如何使用类中定义的类?

转载 作者:行者123 更新时间:2023-11-28 20:45:57 25 4
gpt4 key购买 nike

我正在尝试在一个类中定义一个类。我并不是想用这个来解决现实世界的问题。我只是想通过这段代码学习 Python。

class Foo:
class Bar:
def __init__(self):
self.x = 'Bar'

def __init__(self):
self.x = 'Foo'
self.bar = Bar()

def print(self):
print('self.x:', self.x)
print('self.bar.x:', self.bar.x)

foo = Foo()
foo.print()

当我尝试执行此代码时,出现此错误:

Traceback (most recent call last):
File "demo.py", line 14, in <module>
foo = Foo()
File "demo.py", line 8, in __init__
self.bar = Bar()
NameError: name 'Bar' is not defined

出了什么问题?当我们可以定义和使用函数中定义的函数时,为什么类不一样呢?我在使用 Bar 类时犯了错误吗?

最佳答案

改用 Foo.Bar(),因为 Bar 不是全局名称。

关于python - 如何使用类中定义的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21969241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com