showkey
showkey

Reputation: 298

which position is self in python class?

In the book learning python 5th edition (o'reilly Mark Lutz)page912)

class PrivateExc(Exception): pass                   # More on exceptions in Part VII
class Privacy:
    def __setattr__(self, attrname, value):         # On self.attrname = value
        if attrname in self.privates:
            raise PrivateExc(attrname, self)        # Make, raise user-define except
        else:
            self.__dict__[attrname] = value         # Avoid loops by using dict key
class Test1(Privacy):
    privates = ['age']
class Test2(Privacy):
    privates = ['name', 'pay']
    def __init__(self):
        self.__dict__['name'] = 'Tom'               # To do better, see Chapter 39!

Maybe it is wrong in the 5th lineraise PrivateExc(attrname, self) ,
the self argument will be set as position 1st.
Will be the line changed into raise PrivateExc(self,attrname)?Why not?

Upvotes: 2

Views: 1436

Answers (3)

WKPlus
WKPlus

Reputation: 7255

I think you are just confused about parameters in function definition and function calling.

In a class, a method(instance method) has a non-optional parameter in the first position, usually named self, in the definition, like this:

class Foo:
    def foo(self, another_param): 
        pass

And the self references the instance that you call foo function with. If you have code like this:

f=Foo()
f.foo("test")

self references the f and another_param references the "test" string in the above code.

And then in the foo function, you can use self just like other parameters.

Suppose you have a Print function like this:

def Print(x):
    print "Param:", x

Then you can make you Foo class like this:

class Foo:
    def foo(self, another_param): 
        Print(another_param)  # I think this will not confuse you

Or this:

class Foo:
    def foo(self, another_param): 
        Print(self)  # Now, you may understand this, self is just a param in function calling, like another_param

And now, change the Print function to PrivateExc(you can think it a function to create a PrivateExc instance here), you may understand it either.

Hope these examples can help you understand you question.

Upvotes: 0

Jim Dennis
Jim Dennis

Reputation: 17510

When you are calling a method like this:

#!/bin/python
myinstance.some_method(a,b,c)

... then this is dispatched to some_method as: some_method(myinstance, a, b, c)

The instance through which the method was invoked is passed as your first argument. This is completely different than C++ and Java ... which use an implicit "this" reference ... a pointer valid from within your method's scope but not passed to it as an argument.

I hope that answers your question, thought the code example does nothing to clarify what you're attempting to do.

Upvotes: 1

James Mills
James Mills

Reputation: 19050

Actually it doesn't matter.

Subclassing from Exception without any additional constructor doesn't restrict what you can pass as arguments to the exception class. And you can pass them in any order you want.

The arguments passed to the PrivateExc class just get stored in the instance as the instance attribute .args

Example:

>>> class MyError(Exception):
...     """MyError"""
... 
>>> e = MyError("foo", "bar")
>>> e.args
('foo', 'bar')
>>> e
MyError('foo', 'bar')

What this basically means in the book you're reading is;

If you were to catch the exception PrivateExc you'd do something like this:

try:
    ...
except PrivateExc as error:
   attrname, obj = error.args
   ...

Upvotes: 3

Related Questions