看看这段代码:
class MyClass():
# Why does this give me "NameError: name 'self' is not defined":
mySelf = self
# But this does not?
def myFunction(self):
mySelf2 = self
Run Code Online (Sandbox Code Playgroud)
基本上我想要一个类来引用自己而不需要专门命名自己的方法,因此我希望自己为类工作,而不仅仅是方法/函数.我怎样才能做到这一点?
编辑:这一点是我试图从类内部引用类名称与self之类的东西.class ._ name _这样类名在代码的任何地方都没有硬编码,因此重用代码更容易.
编辑2:从我从下面的答案中学到的,我想要做的是不可能的.我必须找到一种不同的方式.任务放弃了.
编辑3:这是我正在尝试做的事情:
class simpleObject(object):
def __init__(self, request):
self.request = request
@view_defaults(renderer='string')
class Test(simpleObject):
# this line throws an error because of self
myClassName = self.__class__.__name__
@view_config(route_name=myClassName)
def activateTheView(self):
db = self.request.db
foo = 'bar'
return foo
Run Code Online (Sandbox Code Playgroud) python ×1