如何在 Python 中避免显式的“自我"? [英] How to avoid explicit 'self' in Python?

查看:39
本文介绍了如何在 Python 中避免显式的“自我"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习 Python,因为我学习了一些 pygame 教程.

I have been learning Python by following some pygame tutorials.

在其中,我发现关键字 self 被广泛使用,并且主要来自 Java 背景,我发现我一直忘记键入 self.例如,我会输入 rect.centerx 而不是 self.rect.centerx,因为对我来说,rect 已经是班级.

Therein I found extensive use of the keyword self, and coming from a primarily Java background, I find that I keep forgetting to type self. For example, instead of self.rect.centerx I would type rect.centerx, because, to me, rect is already a member variable of the class.

对于这种情况,我能想到的 Java 并行是必须在所有对成员变量的引用前加上 this.

The Java parallel I can think of for this situation is having to prefix all references to member variables with this.

我是否在所有成员变量前都添加了 self 前缀,或者有没有办法声明它们可以让我避免这样做?

Am I stuck prefixing all member variables with self, or is there a way to declare them that would allow me to avoid having to do so?

即使我的建议不是pythonic,我仍然想知道它是否可能.

Even if what I am suggesting isn't pythonic, I'd still like to know if it is possible.

我已经查看了这些相关的 SO 问题,但它们并没有完全回答我的问题:

I have taken a look at these related SO questions, but they don't quite answer what I am after:

推荐答案

Python 需要指定 self. 结果是,即使没有完整的类定义,也不会混淆什么是成员,什么不是成员可见的.这会导致一些有用的属性,例如:您不能添加会意外隐藏非成员从而破坏代码的成员.

Python requires specifying self. The result is there's never any confusion over what's a member and what's not, even without the full class definition visible. This leads to useful properties, such as: you can't add members which accidentally shadow non-members and thereby break code.

一个极端的例子:你可以在不知道它可能有哪些基类的情况下编写一个类,并且总是知道你是否正在访问一个成员:

One extreme example: you can write a class without any knowledge of what base classes it might have, and always know whether you are accessing a member or not:

class A(some_function()):
  def f(self):
    self.member = 42
    self.method()

这就是完整的代码!(some_function 返回用作基础的类型.)

That's the complete code! (some_function returns the type used as a base.)

另一个,类的方法是动态组合的:

Another, where the methods of a class are dynamically composed:

class B(object):
  pass

print B()
# <__main__.B object at 0xb7e4082c>

def B_init(self):
  self.answer = 42
def B_str(self):
  return "<The answer is %s.>" % self.answer
# notice these functions require no knowledge of the actual class
# how hard are they to read and realize that "members" are used?

B.__init__ = B_init
B.__str__ = B_str

print B()
# <The answer is 42.>

记住,这两个例子都是极端的,你不会每天都看到它们,我也不是建议你经常写这样的代码,但它们确实清楚地表明了 self 被明确要求的各个方面.

Remember, both of these examples are extreme and you won't see them every day, nor am I suggesting you should often write code like this, but they do clearly show aspects of self being explicitly required.

这篇关于如何在 Python 中避免显式的“自我"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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