简体   繁体   English

在 Python 中,避免对 __init__ 参数和实例变量使用相同名称的最佳方法是什么?

[英]In Python, what's the best way to avoid using the same name for a __init__ argument and an instance variable?

Whats the best way to initialize instance variables in an init function.init function 中初始化实例变量的最佳方法是什么? Is it poor style to use the same name twice?两次使用同一个名字是不是很糟糕?

class Complex:
     def __init__(self, real, imag):
         self.real = real
         self.imag = imag

It looks sloppy to me to come up with arbitrary alternative names like this:想出这样的任意替代名称对我来说看起来很草率:

class Complex:
     def __init__(self, realpart, imagpart):
         self.r = realpart
         self.i = imagpart

I don't think that this is addressed in the PEP 8 style guide.我认为 PEP 8 风格指南中没有解决这个问题。 It just says that the instance variable and method names should be lower case with underscores separating words.它只是说实例变量和方法名称应该是小写的,用下划线分隔单词。

It is perhaps subjective, but I wouldn't consider it poor style to use the same name twice.这可能是主观的,但我不会认为两次使用相同的名字是不好的风格。 Since self is not implicit in Python, self.real and real are totally distinct and there is no danger of name hiding etc. as you'd experience in other languages (ie C++/Java, where naming parameters like members is somewhat frowned upon).由于self在 Python 中并不隐含,因此self.realreal是完全不同的,并且没有名称隐藏等危险,就像您在其他语言中所经历的那样(即 C++/Java,其中成员等命名参数有些不受欢迎) .

Actually, giving the parameter the same name as the member gives a strong semantic hint that the parameter will map one by one to the member.实际上,为参数赋予与成员相同的名称会给出强烈的语义提示,即参数将 map 一个一个地传递给成员。

There are a couple of reasons to change the name of the underlying instance variable, but it'll depend greatly on what you actually need to do.更改底层实例变量的名称有几个原因,但这在很大程度上取决于您实际需要做什么。 A great example comes with the use of properties.一个很好的例子是使用属性。 You can, for example, create variables that don't get overwritten, which may mean you want to store them under some other variable like so:例如,您可以创建不会被覆盖的变量,这可能意味着您希望将它们存储在其他变量下,如下所示:

class MyClass:
  def __init__(self, x, y):
    self._x, self._y = x, y

  @property
  def x(self):
    return self._x

  @x.setter
  def x(self, value):
    print "X is read only."

  @property
  def y(self):
    return self._y

  @y.setter
  def y(self, value):
    self._y = value

This would create a class that allows you to instantiate with two values, x and y, but where x could not be changed while y could.这将创建一个 class 允许您使用两个值 x 和 y 进行实例化,但其中 x 不能更改而 y 可以。

Generally speaking though, reusing the same name for an instance variable is clear and appropriate.不过一般来说,为实例变量重用相同的名称是明确且适当的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM