python self-less [英] python self-less

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

问题描述

这是以所需的方式工作:

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

我已尝试消除self并使用 __ init __

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()

可能会出现:

a=  2
a=  2

必须使用self?

推荐答案

Python方法只是绑定到类或类的实例的函数。唯一的区别是,一个方法(aka bound函数)期望实例对象作为第一个参数。此外,当从实例调用方法时,它会自动将实例作为第一个参数传递。因此,通过在方法中定义 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.

这样,当您指定 self.a 时,该方法知道您正在修改实例变量 a 是实例命名空间的一部分。

This way when you specify self.a the method knows you're modifying the instance variable a that is part of the instance namespace.

Python范围从内到外工作,因此每个函数(或方法)都有自己的命名空间。如果你从方法 p (这些名字吸引了BTW)中创建了一个变量 a self.a 。使用您的代码的示例:

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 method p (these names suck BTW), it is distinct from that of self.a. Example using your code:

class d:
    def __init__(self,arg):
        self.a = arg
    def p(self):
        a = self.a - 99
        print "my a= ", a
        print "instance a= ",self.a


x = d(1)
y = d(2)
x.p()
y.p()

这产生了:

my a=  -98
instance a=  1
my a=  -97
instance a=  2


$ b b

最后,您不必调用第一个变量 self 。你可以称它为任何你想要的,虽然你真的不应该。从方法中定义和引用 self 是惯例,所以如果你关心别人阅读你的代码,而不想杀了你,坚持约定!

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 reference self from within methods, so if you care at all about other people reading your code without wanting to kill you, stick to the convention!

进一步阅读:

  • Python Classes tutorial

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

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