同名对象范围内的可访问性

时间:2014-01-02 00:43:35

标签: python

如果可能的话,我希望能够在相同的范围内做到这一点:

class blah(object):
    def test(self):
        print 'test'

blah = blah() #global

def test(blah='test')
    print blah
    print 'test 2:' + blah.test()

test()

感谢您的反馈。

*寻找可能的方式(黑客或其他方式)使“blah”执行“test()”而不更改参数“blah”。

1 个答案:

答案 0 :(得分:0)

如果将参数blah传递给函数test,则无法访问blah的全局实例。这是我能为你做的最好的事情。

class Blah(object): # following Python naming conventions, capitalize the class 
    def test(self):
        print 'test'

# now this won't shadow the class definition.
blah = Blah() #global

# you have to be able to differentiate between the function's scope
# and global.  If you name the parameter blah, you cannot access the 
# blah in the global scope.  I renamed it some_blah.
def test(some_blah='test')
    print some_blah
    print 'test 2:' + blah.test()

test()