如何在python中使用global


name = "james"
class Hello:
    global name
    def __init__(self,namek):
        name = namek
        print name
    def sayhi(self):
        print 'Hello my name is', name
a = Hello('john')
a.sayhi()

为什么全局变量名在调用a.sayhi()时没有更改为john ?如下代码所示,x的值改为2

x = 50
def func():
    global x
    print('x is', x)
    x = 2
    print('Changed global x to', x)
func()
print('Value of x is', x)

您需要在方法中声明全局,而不是在类作用域中:

class Hello:
    def __init__(self, namek):
        global name
        name = namek
        print name

我想我应该把这个加进去,因为Martijn已经回答了你的问题。要完成没有global关键字的工作,您可以这样做:

class Hello:
    def __init__(self, namek):
        self.name = namek
        print self.name
    def sayhi(self):
        print 'Hello my name is', self.name
        return self.name

运行时:

>>> name = "james"
>>> print name
james
>>> a = Hello('john')
john # Because we did print self.name in the __init__()
>>> name = a.sayhi()
Hello my name is john
>>> print name
john

相关内容

  • 没有找到相关文章

最新更新