我想使用实例的属性值将默认参数传递给实例方法:
class C:
def __init__(self, format):
self.format = format
def process(self, formatting=self.format):
print(formatting)
Run Code Online (Sandbox Code Playgroud)
尝试时,我收到以下错误消息:
NameError: name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)
我希望该方法的行为如下:
C("abc").process() # prints "abc"
C("abc").process("xyz") # prints "xyz"
Run Code Online (Sandbox Code Playgroud)
这里有什么问题,为什么这不起作用?我怎么能做这个工作?
我一定是在做一些愚蠢的事.我在Google App Engine中运行它:
class MainHandler(webapp.RequestHandler):
def render(self, template_name, template_data):
path = os.path.join(os.path.dirname(__file__), 'static/templates/%s.html' % template_name)
self.response.out.write(template.render(path, template_data)) # error here
def get(self):
self.response.out.write("hi")
def main():
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
这给出了一个错误:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3192, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3135, in _Dispatch
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 516, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2394, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", …Run Code Online (Sandbox Code Playgroud) 我当时正在使用 Python 2.7 编写一个程序,发现自己试图将 Python 类字段作为同一个类中的参数传递。虽然我修改了代码以使其更清晰(从而消除了这种构造的需要),但我仍然很好奇。
对于一些例子(极大地简化,但概念是存在的):
[注意:对于示例 1 和 2,假设我想要将一个数字作为输入并递增它,或者递增当前值。]
示例 1。
class Example:
def __init__(self,x):
self.value = x
def incr(self,x=self.value):
self.value = x + 1
Run Code Online (Sandbox Code Playgroud)
结果:
"NameError: name 'self' is not defined"
Run Code Online (Sandbox Code Playgroud)
示例 2.
class Example:
def __init__(self,x):
self.value = x
def incr(self,x=value):
self.value = x + 1
Run Code Online (Sandbox Code Playgroud)
结果:
"NameError: name 'value' is not defined"
Run Code Online (Sandbox Code Playgroud)
示例 3.
class Example:
def __init__(self,x):
ex2 = Example2()
self.value = ex2.incr(x)
def get_value(self):
return self.value
class Example2:
def __init__(self):
self.value = 0 …Run Code Online (Sandbox Code Playgroud) 如何self.value在函数定义中调用 a ?
class toto :
def __init__(self):
self.titi = "titi"
def printiti(self,titi=self.titi):
print(titi)
Run Code Online (Sandbox Code Playgroud)