蟒蛇无私
这以期望的方式工作:
class d:
def __init__(self,arg):
self.a = arg
def p(self):
print "a= ",self.a
x = d(1)
y = d(2)
x.p()
y.p()
产生
a= 1
a= 2
我尝试消除“self”并在 __init__
中使用全局语句
class d:
def __init__(self,arg):
global a
a = arg
def p(self):
print "a= ",a
x = d(1)
y = d(2)
x.p()
y.p()
产生,不合需要:
a= 2
a= 2
有没有一种方法可以在不使用“self”的情况下编写它?
this works in the desired way:
class d:
def __init__(self,arg):
self.a = arg
def p(self):
print "a= ",self.a
x = d(1)
y = d(2)
x.p()
y.p()
yielding
a= 1
a= 2
i've tried eliminating the "self"s and using a global statement in __init__
class d:
def __init__(self,arg):
global a
a = arg
def p(self):
print "a= ",a
x = d(1)
y = d(2)
x.p()
y.p()
yielding, undesirably:
a= 2
a= 2
is there a way to write it without having to use "self"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“self”是Python 的工作方式。所以答案是:不!如果你想剪头发:你不必使用“自我”。任何其他名称也可以。 ;-)
"self" is the way how Python works. So the answer is: No! If you want to cut hair: You don't have to use "self". Any other name will do also. ;-)
Python 方法只是绑定到类或类实例的函数。唯一的区别是方法(也称为绑定函数)需要实例对象作为第一个参数。此外,当您从实例调用方法时,它会自动将该实例作为第一个参数传递。因此,通过在方法中定义 self,您可以告诉它要使用的名称空间。
这样,当您指定
self.a
时,该方法就知道您正在修改属于实例命名空间一部分的实例变量a
。Python 作用域是从内到外工作的,因此每个函数(或方法)都有自己的命名空间。如果您从方法
p
中本地创建一个变量a
(顺便说一句,这些名称很糟糕),它与self.a
的变量不同。使用您的代码的示例:产生:
最后,您不必调用第一个变量
self
。你可以随心所欲地称呼它,尽管你确实不应该这样做。从方法内部定义和引用 self 是一种约定,因此,如果您非常关心其他人阅读您的代码而不是想杀死您,请遵守约定!进一步阅读:
Python methods are just functions that are bound to the class or instance of a class. The only difference is that a method (aka bound function) expects the instance object as the first argument. Additionally when you invoke a method from an instance, it automatically passes the instance as the first argument. So by defining
self
in a method, you're telling it the namespace to work with.This way when you specify
self.a
the method knows you're modifying the instance variablea
that is part of the instance namespace.Python scoping works from the inside out, so each function (or method) has its own namespace. If you create a variable
a
locally from within the methodp
(these names suck BTW), it is distinct from that ofself.a
. Example using your code:Which yields:
Lastly, you don't have to call the first variable
self
. You could call it whatever you want, although you really shouldn't. It's convention to define and referenceself
from within methods, so if you care at all about other people reading your code without wanting to kill you, stick to the convention!Further reading:
当您删除 self 时,最终只有一个名为
a
的变量,该变量不仅会在所有d
对象之间共享,还会在整个执行环境中共享。你不能因此就消除自我。
When you remove the self's, you end up having only one variable called
a
that will be shared not only amongst all yourd
objects but also in your entire execution environment.You can't just eliminate the self's for this reason.