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