gpt4 book ai didi

python - 对象如何访问其所有者的全局对象?

转载 作者:行者123 更新时间:2023-12-01 04:55:50 24 4
gpt4 key购买 nike

如果我们有类似的东西:

foo.py

from bar import bar

class foo:
global black;
black = True;

bar = bar()

bar.speak()

f = foo()

bar.py

class bar:
def speak():
if black:
print "blaaack!"
else:
print "whitttte!"

当我们运行时python foo.py

我们得到

NameError:未定义全局名称“black”

做这样的事情的最佳实践是什么?

我应该在方法中传递它吗?

bar 类有父变量吗?

对于上下文,实际上 black 全局用于调试步骤。

最佳答案

在 Python 中,全局变量特定于模块。所以你的 foo.py 中的全局在你的 bar.py 中是不可访问的——至少不是你写的方式。

如果您希望 foo 的每个实例都有自己的 black 值,请使用实例变量,如 Ivelin 所示。如果您希望 foo 的每个实例共享相同的 black 值,请使用类变量。

<小时/>

使用实例变量:

# foo.py
from bar import bar

class foo:
# Python "constructor"..
def __init__(self):
# Define the instance variables
self.bar = bar()
# Make bar talk
self.bar.speak()

# Create a function for making this foo's bar speak whenever we want
def bar_speak(self):
self.bar.speak()

################################################################################
# bar.py
class bar:
# Python "constructor"..
def __init__(self):
# Define the instance variables
self.black = True
def speak(self):
if self.black:
print "blaaack!"
else:
print "whitttte!"

使用代码:

>>> f = foo()
blaaack!
>>> b = foo()
blaaack!
>>> b.bar.black = False
>>> b.bar_speak()
whitttte!
>>> f.bar_speak()
blaaack!
<小时/>

使用类变量:

# foo.py
from bar import bar

class foo:
# Python "constructor"..
def __init__(self):
# Define the instance variables
self.bar = bar()
# Make bar talk
self.bar.speak()

# Create a function for making this foo's bar speak whenever we want
def bar_speak(self):
self.bar.speak()

################################################################################
# bar.py
class bar:
black = True
def speak():
if bar.black:
print "blaaack!"
else:
print "whitttte!"

使用代码:

>>> f = foo()
blaaack!
>>> b = foo()
blaaack!
>>> bar.black = False
>>> b.bar_speak()
whitttte!
>>> f.bar_speak()
whitttte!

关于python - 对象如何访问其所有者的全局对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27414949/

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