在Python中,避免对__init__参数和实例变量使用相同的名称的最好方法是什么? [英] In Python, what's the best way to avoid using the same name for a __init__ argument and an instance variable?

查看:211
本文介绍了在Python中,避免对__init__参数和实例变量使用相同的名称的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

init 函数中初始化实例变量的最佳方法是什么。

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

我不认为这是在PEP 8风格指南中解决。它只是说,实例变量和方法名称应该是小写,下划线分隔单词。

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.

推荐答案

这可能是主观的,但我不会认为它糟糕的风格使用相同的名称两次。由于 self 在Python中不是隐含的, self.real real 是完全不同的,没有名称隐藏的危险等,因为你会体验到其他语言(即C ++ / Java,其中命名参数像成员有点皱眉)。

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.

这篇关于在Python中,避免对__init__参数和实例变量使用相同的名称的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆