Python'self'关键字 [英] Python 'self' keyword

查看:46
本文介绍了Python'self'关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手(通常使用 C#),最近几天开始使用它.

I am new to Python (usually work on C#), started using it over the last couple of days.

在一个类中,您是否需要在对该类数据成员和方法的任何调用前加上前缀?因此,如果我从该类中调用方法或从该类中获取值,则需要使用 self.method()self.intvalue,例如例子?

Within a class, do you need to prefix any call to that classes data members and methods? So, if I am calling a method or obtaining a value from that class, from within that class, I need to use self.method() or self.intvalue, for example?

我只是想检查一下我还没有遇到过的不那么冗长的方法.

I just want to check that there isn't a less verbose way that I have not encountered yet.

推荐答案

没有比这更冗长的方法了.始终使用self.x 来访问实例属性x.请注意,与 C++ 中的 this 不同,self 不是关键字.你可以为你的方法的第一个参数提供任何你想要的名字,但强烈建议你坚持调用它self的约定.

There is no less verbose way. Always use self.x to access the instance attribute x. Note that unlike this in C++, self is not a keyword, though. You could give the first parameter of your method any name you want, but you are strongly advised to stick to the convention of calling it self.

这篇关于Python'self'关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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