Python:如何使实例变量可用? [英] Python: How should I make instance variables available?

查看:71
本文介绍了Python:如何使实例变量可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

class myclass:
  def __init__(self):
    self.foo = "bar"

其中foo的值必须可供myclass用户使用。直接从myclass实例中读取foo的值是否可以?我应该将get_foo方法添加到myclass还是应该添加foo属性?此处的最佳做法是什么?

where the value of foo needs to be available to users of myclass. Is it OK to just read the value of foo directly from an instance of myclass? Should I add a get_foo method to myclass or perhaps add a foo property? What's the best practice here?

推荐答案

适用的Python格言是我们都是成年人-如果用户需要直接访问 foo 的值,让他们直接访问它。如果您需要在访问代码时运行一些代码,则使用getter或属性是有意义的,否则直接方法是最好的方法。

The applicable Python maxim would be "we're all adults here" - if users need direct access to the value of foo, let them access it directly. A getter or property would make sense if you need to run some code when it's accessed, otherwise the direct way is best.

此外,您以后随时可以根据需要将其透明地转换为属性。

Also, you can always transparently turn it into a property later if you need to.

这篇关于Python:如何使实例变量可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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