473,406 Members | 2,343 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

def index(self):

Is there a difference between

<code>
class HelloWorld:
def index(self):
index.exposed = True
return "Hello world!"
</code>

and

<code>
class HelloWorld:
def index(self):
self.exposed = True
return "Hello world!"
</code>
Dec 18 '06 #1
14 5080
Gert Cuykens kirjoitti:
Is there a difference between

<code>
class HelloWorld:
def index(self):
index.exposed = True
return "Hello world!"
</code>

and

<code>
class HelloWorld:
def index(self):
self.exposed = True
return "Hello world!"
</code>
The resident experts seemingly being absent for a while, I'll strike:

Yes: the first gives a runtime error and the second is OK.
I've renamed the second class to HelloWorld2 and then:
>>hw = HelloWorld()
hw2 = HelloWorld2()
>>hw.index()
Traceback (most recent call last):
File "<pyshell#144>", line 1, in <module>
hw.index()
File "C:\Python\Dive into Python\Py\apihelper.py", line 40, in index
index.exposed = True
NameError: global name 'index' is not defined
>>hw2.index()
'Hello world!'

The error message shows that the Python compiler has interpreted the
construction 'index.exposed' to refer to a global variable 'index' that
doesn't exist at run time. The second class succesfully defines an
instance attribute 'exposed' as can be seen by:
>>print hw2.exposed
True

HTH
Jussi
Dec 18 '06 #2
Gert Cuykens a écrit :
Is there a difference between

<code>
class HelloWorld:
def index(self):
index.exposed = True
return "Hello world!"
</code>

and

<code>
class HelloWorld:
def index(self):
self.exposed = True
return "Hello world!"
</code>
Ask yourself what are the names 'index' and 'self' refering to in the
context of this function, and you'll have the answer. And if you can't
answer, then it may be time to learn Python...

FWIW, the first version raises an exception (unless of course the name
'index' is already bound in the enclosing scope). And the second won't
probably work as expected with CherryPy.

Dec 18 '06 #3
FWIW, the first version raises an exception (unless of course the name
'index' is already bound in the enclosing scope). And the second won't
probably work as expected with CherryPy.
<code>
class HelloWorld:
def index(self):
return "Hello world!"
index.exposed = True #DOOOOOOH!
</code>

i skipped reading the chapter about 2.1.8 Indentation. Guess how many
hours it took to realize 2 spaces isn't the same as 1 space lol

Any other chapters i should read horizontal instead of vertical for a
php5 htm jso wane be snake user :)
Dec 18 '06 #4
Gert Cuykens a écrit :
>FWIW, the first version raises an exception (unless of course the name
'index' is already bound in the enclosing scope). And the second won't
probably work as expected with CherryPy.


<code>
class HelloWorld:
def index(self):
return "Hello world!"
index.exposed = True #DOOOOOOH!
And the winner is....
</code>

i skipped reading the chapter about 2.1.8 Indentation. Guess how many
hours it took to realize 2 spaces isn't the same as 1 space lol
Hint:
- use a good code editor with auto(de)indentation (emacs + python-mode
is quite nice)
- use 4 spaces for indentation
Any other chapters i should read horizontal instead of vertical for a
php5 htm jso wane be snake user :)
The whole thing, I guess. While Python is quite easy to get started
with, there are a few gotchas. You're above snippet should be:

class HelloWorld(object):
def index(self):
return "Hello World"
index.exposed = True
Dec 19 '06 #5
Bruno Desthuilliers <bd*****************@free.quelquepart.frwrote:
>
Gert Cuykens a écrit :
>>FWIW, the first version raises an exception (unless of course the name
'index' is already bound in the enclosing scope). And the second won't
probably work as expected with CherryPy.

<code>
class HelloWorld:
def index(self):
return "Hello world!"
index.exposed = True #DOOOOOOH!

And the winner is....
></code>

The whole thing, I guess. While Python is quite easy to get started
with, there are a few gotchas. You're above snippet should be:

class HelloWorld(object):
def index(self):
return "Hello World"
index.exposed = True
Many people find it more readable to write that as:

class HelloWorld(object):
@cherrypy.exposed
def index(self):
return "Hello World"

I haven't decided yet.
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Dec 20 '06 #6
Tim Roberts a écrit :
Bruno Desthuilliers <bd*****************@free.quelquepart.frwrote:
>>Gert Cuykens a écrit :
>>>>FWIW, the first version raises an exception (unless of course the name
'index' is already bound in the enclosing scope). And the second won't
probably work as expected with CherryPy.

<code>
class HelloWorld:
def index(self):
return "Hello world!"
index.exposed = True #DOOOOOOH!

And the winner is....

>>></code>

The whole thing, I guess. While Python is quite easy to get started
with, there are a few gotchas. You're above snippet should be:

class HelloWorld(object):
def index(self):
return "Hello World"
index.exposed = True


Many people find it more readable to write that as:

class HelloWorld(object):
@cherrypy.exposed
def index(self):
return "Hello World"
So do I. But this breaks compatibility with older Python versions, and
is perhaps a bit confusing for someone that doesn't seem to really get
some basic Python stuffs like what 'self' is...

My 2 cents
Dec 20 '06 #7
class HelloWorld(object):
@cherrypy.exposed
def index(self):
return "Hello World"
do i have to write @cherrypy.exposed before every def or just once for
all the def's ? and why not write something like @index.exposed ?

in other words i have no idea what @ actually does i only know i have
too write it to make it work :) Am guessing @ is something like
prototyping in javascript but then def index is not a object but a
method ? So that would not make sense ?

oh and self stands more or less for private method right ?
Dec 20 '06 #8
Gert Cuykens wrote:
class HelloWorld(object):
@cherrypy.exposed
def index(self):
return "Hello World"

do i have to write @cherrypy.exposed before every def or just once for
all the def's ? and why not write something like @index.exposed ?

in other words i have no idea what @ actually does i only know i have
too write it to make it work :) Am guessing @ is something like
prototyping in javascript but then def index is not a object but a
method ? So that would not make sense ?

oh and self stands more or less for private method right ?
Ouch. Do you really expect to learn a language from scratch by Q&A in a
malining list ? That's a very inefficient way to spend both yours and
others' time. Do your homework first by reading one of the several free
tutorials online and come back when you have trouble with something
specific you didn't understand.

George

Dec 21 '06 #9
"George Sakkis" <ge***********@gmail.comwrote:
Gert Cuykens wrote:
class HelloWorld(object):
@cherrypy.exposed
def index(self):
return "Hello World"

do i have to write @cherrypy.exposed before every def or just once
for all the def's ? and why not write something like @index.exposed ?

in other words i have no idea what @ actually does i only know i have
too write it to make it work :) Am guessing @ is something like
prototyping in javascript but then def index is not a object but a
method ? So that would not make sense ?

oh and self stands more or less for private method right ?

Ouch. Do you really expect to learn a language from scratch by Q&A in
a malining list ? That's a very inefficient way to spend both yours
and others' time. Do your homework first by reading one of the several
free tutorials online and come back when you have trouble with
something specific you didn't understand.
To be perfectly fair, searching for information about decorators if you
don't know what they are called is kind of hard. Searching for
information about the '@' character in the Python documentation doesn't
lead to much. The CherryPy tutorial does at least mention this
decorator, just not in any meaningful way:
Exposing objects

CherryPy maps URL requests to objects and calls the suitable method
automatically. The methods that can be called as a result of external
requests are said to be exposed.

Objects are exposed in CherryPy by setting the exposed attribute. This
an be done directly on the object itself: object.exposed = True.
Methods can also be exposed using a special decorator:

Why this distinction?

The distinction between published and exposed objects may seem silly
or unnecessary at first. By definition, all exposed objects are also
published, so why do we need to care about non-exposed objects?
To the OP:

do i have to write @cherrypy.exposed before every def or just once for
all the def's ?
Before every def that you wish to expose, which won't be all of them.
and why not write something like @index.exposed ?
because that isn't how it works. cherrypy.exposed is a decorator, which
means it is a function that takes a function as an argument modifies it in
some way and returns the modified function as its result.
>
in other words i have no idea what @ actually does i only know i have
too write it to make it work :) Am guessing @ is something like
prototyping in javascript but then def index is not a object but a
method ? So that would not make sense ?
@expr
def fn(...): ...

is exactly equivalent to:

def fn(...): ...
fn = (expr)(fn)

except that at the point when the decorator is called the function has not
yet been assigned to the name 'fn'. (Also remember that def is an
executable statement so it happens when the line containing the def is
execfuted, and that names assigned to functions are just like other
variable names and can be rebound at will.)
>
oh and self stands more or less for private method right ?
if you have to ask that question about 'self' you really do need to read
some introductory texts on Python.

Methods get passed their instance as their first parameter (usually this is
implicit in the call, but it is always explicitly shown in the method) and
self is simply the conventional name. Many other languages use 'this'
instead of self and make the passing of 'this' implicit inside the method
as well as outside. There are good reasons why it is explicit in Python,
but just remember that the first parameter a method receives is always the
instance and you won't go far wrong.
Dec 21 '06 #10
On 21 Dec 2006 09:44:48 GMT, Duncan Booth <du**********@invalid.invalidwrote:
"George Sakkis" <ge***********@gmail.comwrote:

@expr
def fn(...): ...

is exactly equivalent to:

def fn(...): ...
fn = (expr)(fn)
ok i did my homework reading about decorators
http://www.python.org/doc/2.4.4/whatsnew/node6.html

could it be the example above needs to be like

@expr
def fn(...): ...

is exactly equivalent to:

def fn(...): ...
fn = expr(fn)
oh and self stands more or less for private method right ?

if you have to ask that question about 'self' you really do need to read
some introductory texts on Python.

Methods get passed their instance as their first parameter (usually this is
implicit in the call, but it is always explicitly shown in the method) and
self is simply the conventional name. Many other languages use 'this'
instead of self and make the passing of 'this' implicit inside the method
as well as outside. There are good reasons why it is explicit in Python,
but just remember that the first parameter a method receives is always the
instance and you won't go far wrong.
in all the things i every read about self i end up with blablabla
scoping blabla blabla self:: blablabla public static methods blablabla
:)

So when reading 'self' is the same as 'this' it was worth asking the
question for confusion sake :)
Dec 21 '06 #11
In <ma***************************************@python. org>, Gert Cuykens
wrote:
On 21 Dec 2006 09:44:48 GMT, Duncan Booth <du**********@invalid.invalidwrote:
>"George Sakkis" <ge***********@gmail.comwrote:

@expr
def fn(...): ...

is exactly equivalent to:

def fn(...): ...
fn = (expr)(fn)

ok i did my homework reading about decorators
http://www.python.org/doc/2.4.4/whatsnew/node6.html

could it be the example above needs to be like

@expr
def fn(...): ...

is exactly equivalent to:

def fn(...): ...
fn = expr(fn)
This depends on the definition of `expr`. If `expr` includes the
possibility of enclosing parenthesis then yes. There are scenarios where
you would need them. For example if you use objects that overload
operators to build a callable used as decorator:

@spam + eggs + viking
def fn(...): ...

This would not be equivalent to:

def fn(...): ...
fn = spam + eggs + viking(fn)

but:

def fn(...): ...
fn = (spam + eggs + viking)(fn)

Ciao,
Marc 'BlackJack' Rintsch
Dec 22 '06 #12
Marc 'BlackJack' Rintsch wrote:
This depends on the definition of `expr`. If `expr` includes the
possibility of enclosing parenthesis then yes. There are scenarios where
you would need them. For example if you use objects that overload
operators to build a callable used as decorator:

@spam + eggs + viking
def fn(...): ...
that's a SyntaxError. the decorator syntax only allows for a dotted
name, optionally followed by an argument list in parentheses.

</F>

Dec 22 '06 #13
"Gert Cuykens" <ge**********@gmail.comwrote:
On 21 Dec 2006 09:44:48 GMT, Duncan Booth
<du**********@invalid.invalidwrote:
>"George Sakkis" <ge***********@gmail.comwrote:

@expr
def fn(...): ...

is exactly equivalent to:

def fn(...): ...
fn = (expr)(fn)

ok i did my homework reading about decorators
http://www.python.org/doc/2.4.4/whatsnew/node6.html

could it be the example above needs to be like

@expr
def fn(...): ...

is exactly equivalent to:

def fn(...): ...
fn = expr(fn)
no it doesn't *need* to be like that, but it *could* be written like that.
It is true that the parentheses I used are redundant (I thought they made
my point clearer), but removing redundant parentheses doesn't actually
change the meaning at all.

In any case, either of these rewrites is an approximation. There is no
Python code you can write which is exactly equivalent to, but doesn't use,
the decorator syntax. A closer approximation would be:

If you consider:

def fn(...): ...

is equivalent to writing:

fn = new.function(somecodeobject, globals(), 'fn', (...default argument
expressions...), ...and maybe a closure...)

then:

@expr
def fn(...): ...

is equivalent to writing:

__anonymous_temp_1 = expr
__anonymous_temp_2 = new.function(somecodeobject, globals(), 'fn',
(...default argument expressions...), ...and maybe a closure...)
fn = __anonymous_temp_1(__anonymous_temp_2)

but I don't think that is really any clearer.

It does perhaps indicate the order in which things happen more clearly:
decorator expression is evaluated, then default arguments, then function is
created, then decorator is called, then finally the result is assigned to a
variable with the same name as the function.
Dec 22 '06 #14
Ok thx i think i understand it now
>>class C:
.... @staticmethod
.... def fn():
.... return 'whohoo'
....
>>C.fn()
'whohoo'
>>>
Dec 22 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: aurora | last post by:
This may sound a little crazy. I capture the output of one class by redirecting the sys.stdout. However the is another threading running at the same time and occasionaly it output some messages to...
9
by: kosh | last post by:
I was wondering if there is or there could be some way to pass a generator an optional starting index so that if it supported that slicing could be made more efficient. Right now if you do use a...
4
by: techiepundit | last post by:
I'm a Python newbie who just started learning the language a few weeks ago. So these are beginner questions. I have a list of sockets that I use for select.select calls like this: ...
35
by: erikwickstrom | last post by:
Hi all, I'm sorry about the newbie question, but I've been searching all afternoon and can't find the answer! I'm trying to get this bit of code to work without triggering the IndexError. ...
5
by: vd12005 | last post by:
Hello, While playing to write an inverted index (see: http://en.wikipedia.org/wiki/Inverted_index), i run out of memory with a classic dict, (i have thousand of documents and millions of terms,...
3
by: Kevin Walzer | last post by:
I'm trying to set the active item in a Tkinter listbox to my application's currently-defined default font. Here's how I get the fonts loaded into the listbox: ...
122
by: C.L. | last post by:
I was looking for a function or method that would return the index to the first matching element in a list. Coming from a C++ STL background, I thought it might be called "find". My first stop was...
6
by: xkenneth | last post by:
Looking to do something similair. I'm working with alot of timestamps and if they're within a couple seconds I need them to be indexed and removed from a list. Is there any possible way to index...
3
by: Riccardo Murri | last post by:
Hello, I have some code that stops when trying to find a graph in a list of similar graphs:: (Pydb) list 110 try: 111 canonical = self.base 112 except ValueError: 113 ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.