在函数参数定义中使用self

2024-04-23 20:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

而不是执行以下操作:

def MyFunc(self, a, b, c)
    self.a = a
    self.b = b
    self.c = c

我想做以下工作:

def MyFunc(self, self.a, self.b, self.c)

为什么这样不行?你知道吗

如果我必须使用第一种方法,是否有什么好方法确保我不会无意中用相同的名称覆盖项目中其他地方使用的变量(例如,“a”可能是另一个对象使用的变量)。你知道吗


Tags: 项目对象方法self名称def地方myfunc
1条回答
网友
1楼 · 发布于 2024-04-23 20:28:59

Instead of doing the following:

def MyFunc(self, a, b, c)
    self.a = a
    self.b = b
    self.c = c

I want to do the following:

def MyFunc(self, self.a, self.b, self.c)

Why does this not work?

这不起作用,因为它只是无效的语法。Python将不允许您使用self.,因为您的语法无效。让我们看看Python中函数参数的EBNF

parameters: '(' [typedargslist] ')'

typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [','
  ['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' >tfpdef]]
|  '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' >tfpdef)

tfpdef: NAME [':' test]

您可以从上面的EBNF片段中分辨出来,也可以从中分辨不出来,但是Python不允许在参数中使用.操作符。这就是为什么你的第二种方法不起作用。你知道吗

不过,让我们假设您的第二个示例是有效的Python语法。行吗?简而言之,答案仍然是否定的。这很简单,因为Python是如何解析函数/方法参数的。让我们看看这个例子:

>>> class Foo:
    def __init__(self):
        pass
    def bar(self, x=self):
        pass


Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    class Foo:
  File "<pyshell#13>", line 4, in Foo
    def bar(self, x=self):
NameError: name 'self' is not defined
>>> 

发生什么事了?当self被清楚地定义时,Python为什么要提出一个NameError。你知道吗

当Python正在解析时,bar可以看到参数self。但是,虽然Python已经“看到”了self参数,但它没有将其定义为名称。因此,当Python试图解析第二个参数时,它会变得混乱,并引发NameError。这种行为不仅限于 方法。函数也有同样的问题:

>>> def foo(a, b=a+1):
    return a, b

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    def foo(a, b=a+1):
NameError: name 'a' is not defined

总之,real第二个示例不起作用的原因是它是无效的Python语法。但是,即使它以某种方式工作,Python仍然会由于其解析参数的方式而引发错误。你知道吗

相关问题 更多 >