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

冷暖自知 提交于 2019-12-11 03:11:23

问题


Whats the best way to initialize instance variables in an 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. It just says that the instance variable and method names should be lower case with underscores separating words.


回答1:


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 (i.e. C++/Java, where naming parameters like members is somewhat frowned upon).

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.




回答2:


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.

Generally speaking though, reusing the same name for an instance variable is clear and appropriate.



来源:https://stackoverflow.com/questions/5821387/in-python-whats-the-best-way-to-avoid-using-the-same-name-for-a-init-argum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!