是否所有成员变量都应在__init__中初始化 [英] Should all member variables be initialized in __init__

查看:106
本文介绍了是否所有成员变量都应在__init__中初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这比技术问题更像是一个样式问题,但是我有一个包含多个成员变量的类,我想让它起作用,以便在用户第一次创建该类的实例时初始化一些成员变量(即在__init__函数中),我希望从成员函数的参数中定义其他成员变量,稍后将对其进行调用.因此,我的问题是我应该初始化__init__函数中的所有成员变量(并将稍后定义的变量设置为虚拟值)还是初始化__init__函数中的某些成员变量以及稍后函数中的某些成员变量.我意识到这可能很难理解,因此这里有一些示例.

Maybe this is more of a style question than a technical one but I have a class with several member variables and I want to have it work so that some of the member variables are initialized when the user first creates an instance of the class (i.e. in the __init__ function) and I want the other member variables to be defined from arguments of member functions that will be called later on. So my question is should I initialize all member variables in the __init__ function (and set the ones that will be defined later on to dummy values) or initialize some in the __init__ function and some in later functions. I realize this might be difficult to understand so here are a couple of examples.

此示例最初在__init__函数中将var3设置为0,然后在my_funct函数中随后将其设置为所需值.

This example has var3 set to 0 initially in the __init__ function, then set to the desired value later on in the my_funct function.

class myClass(object):
   def __init__(self,var1,var2):
        self.var1=var1
        self.var2=var2
        self.var3=0

  def my_funct(self,var3):
       self.var3=var3

,在本示例中,__init__函数中根本没有定义var3

and in this example, var3 is not defined at all in the __init__ function

class myClass(object):
   def __init__(self,var1,var2):
        self.var1=var1
        self.var2=var2

  def my_funct(self,var3):
       self.var3=var3

我不认为任何一种方法都会有很大的不同(也许在内存使用上有细微的差别).但我想知道由于某种原因,其中一个是否比另一个更受欢迎.

I don't think either way would make a big difference (maybe a slight difference in memory usage). But I was wondering if one of these is preferred over the other for some reason.

推荐答案

在面向对象的程序设计中,开发人员应确保在实例化和方法完成之后,对象始终处于一致状态.除此之外,您还可以随意开发类(请记住带有子类化/重写等的某些原则).

In object-oriented programming it's up to the developer to ensure an object is always in a consistent state after instantiation and after a method finishes. Other than that you're free to develop the class as you wish (keeping in mind certain principles with subclassing / overriding and so on).

__init__外部设置实例变量时,会警告诸如 Pylint 之类的工具.可以争辩说,在__init__中设置所有实例变量更为简洁,但这并不是始终必须遵守的规则.

A tool such as Pylint will warn when you're setting instance variables outside __init__. It can be argued that setting all instance variables in the __init__ is cleaner but it's not a rule that must be abided by at all times.

这篇关于是否所有成员变量都应在__init__中初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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