坏练习在构造函数中运行代码可能失败? [英] Bad Practice to run code in constructor thats likely to fail?

查看:175
本文介绍了坏练习在构造函数中运行代码可能失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是一个设计问题。
在Python中,如果你的构造函数中的代码失败,对象最终没有被定义。因此:

my question is rather a design question. In Python, if code in your "constructor" fails, the object ends up not being defined. Thus:

someInstance = MyClass("test123") #lets say that constructor throws an exception
someInstance.doSomething() # will fail, name someInstance not defined.

我有一种情况,如果我删除错误,从我的构造函数。基本上我的构造函数填充了一些属性(通过IO,其中很多可能出错),可以使用各种getter访问。如果我从植入者中删除代码,我有10个getters与复制粘贴代码,如:

I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like :


  1. 是属性真的设置? / li>
  2. 执行一些IO操作以填充属性

  3. 返回问题变量的内容

我不喜欢,因为所有的getter都会包含很多代码。而不是我在一个中央位置执行我的IO操作,构造函数,并填充我的所有属性。

I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes.

这是一个正确的方法是什么?

Whats a proper way of doing this?

推荐答案

我不是一个Python开发人员,但一般来说,最好避免复杂/容易出错的操作。一种方法是在类中放置一个LoadFromFile或Init方法,以从外部源填充对象。这个load / init方法必须在构造对象后单独调用。

I'm not a Python developer, but in general, it's best to avoid complex/error-prone operations in your constructor. One way around this would be to put a "LoadFromFile" or "Init" method in your class to populate the object from an external source. This load/init method must then be called separately after constructing the object.

这篇关于坏练习在构造函数中运行代码可能失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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