简体   繁体   中英

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. 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.

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).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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