user717751
user717751

Reputation:

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

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"?

Upvotes: 4

Views: 712

Answers (3)

jathanism
jathanism

Reputation: 33716

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

Which yields:

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

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!

Further reading:

Upvotes: 4

chandsie
chandsie

Reputation: 2895

When you remove the self's, you end up having only one variable called a that will be shared not only amongst all your d objects but also in your entire execution environment. You can't just eliminate the self's for this reason.

Upvotes: 0

Achim
Achim

Reputation: 15702

"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. ;-)

Upvotes: 6

Related Questions