In Python, what's the best way to avoid using

2019-07-18 18:56发布

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.

2条回答
Luminary・发光体
2楼-- · 2019-07-18 19:20

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.

查看更多
一夜七次
3楼-- · 2019-07-18 19:26

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.

查看更多
登录 后发表回答