How do I program something like the folowing program?
PYTHON claims it doesn't know about 'foo' when initializing K!
The only way I got this to work was doing the init of K in
the __init__ func. But this runs everytime for each object!
When using the name of the function without 'foo', I don't
know how to call it!
Thanks for any help.
#! /bin/env python
# -*- coding: iso-8859-15 -*-
class foo:
def f1():
print "f1"
f1=staticmethod(f1)
def f2():
print "f2"
f2=staticmethod(f2)
K={"f1" : foo.f1, \
"f1" : foo.f2 \
}
def main():
foo.K["f1"]()
foo.K["f2"]()
if __name__ == "__main__":
main() 15 1462
Paulo da Silva wrote: How do I program something like the folowing program? PYTHON claims it doesn't know about 'foo' when initializing K! The only way I got this to work was doing the init of K in the __init__ func. But this runs everytime for each object! When using the name of the function without 'foo', I don't know how to call it!
Thanks for any help.
#! /bin/env python # -*- coding: iso-8859-15 -*-
class foo: def f1(): print "f1" f1=staticmethod(f1)
def f2(): print "f2" f2=staticmethod(f2)
K={"f1" : foo.f1, \ "f1" : foo.f2 \ }
def main(): foo.K["f1"]() foo.K["f2"]()
if __name__ == "__main__": main()
self.f1 and self.f2 should work within any class. Try that.
Well, I tried self and it said the same as with foo. So I just called
f1() and f2() without self or foo in front since they should be within
scope and it worked to that extent but complained further, see below:
File
"C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py" ,
line 310, in RunScript
exec codeObject in __main__.__dict__
File "..\My Documents\CODE\test_dumpscript.py", line 20, in ?
main()
File "..\My Documents\CODE\test_dumpscript.py", line 16, in main
foo.K["f1"]()
TypeError: 'staticmethod' object is not callable
How do I program something like the folowing program? PYTHON claims it doesn't know about 'foo' when initializing K! The only way I got this to work was doing the init of K in the __init__ func. But this runs everytime for each object! When using the name of the function without 'foo', I don't know how to call it!
Thanks for any help.
#! /bin/env python # -*- coding: iso-8859-15 -*-
class foo: def f1(): print "f1" f1=staticmethod(f1)
def f2(): print "f2" f2=staticmethod(f2)
K={"f1" : foo.f1, \ "f1" : foo.f2 \ }
def main(): foo.K["f1"]() foo.K["f2"]()
if __name__ == "__main__": main()
Paulo da Silva wrote: How do I program something like the folowing program? PYTHON claims it doesn't know about 'foo' when initializing K! The only way I got this to work was doing the init of K in the __init__ func. But this runs everytime for each object! When using the name of the function without 'foo', I don't know how to call it!
Thanks for any help.
Move the table outside of the class definition
class foo(object):
def f1():
print 'f1'
f1 = staticmethod(f1)
foo.K = {'f1': foo.f1,
}
foo.K['f1']()
--
Robert Kern rk***@ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
Robert Kern wrote: Paulo da Silva wrote:
How do I program something like the folowing program? PYTHON claims it doesn't know about 'foo' when initializing K! The only way I got this to work was doing the init of K in the __init__ func. But this runs everytime for each object! When using the name of the function without 'foo', I don't know how to call it!
Thanks for any help.
Move the table outside of the class definition
class foo(object): def f1(): print 'f1' f1 = staticmethod(f1)
foo.K = {'f1': foo.f1, }
foo.K['f1']()
Right Right Right.
Notice how he added the "object" as an arg to class foo.
<SNIP>
Move the table outside of the class definition
class foo(object): def f1(): print 'f1' f1 = staticmethod(f1)
foo.K = {'f1': foo.f1, }
foo.K['f1']()
Right Right Right. Notice how he added the "object" as an arg to class foo.
Now that I think of it some more, why did you add that object arg?
That's not necessary.
Richard Blackwood wrote:
[snip] Now that I think of it some more, why did you add that object arg? That's not necessary.
Habit.
--
Robert Kern rk***@ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
Paulo da Silva wrote: class foo: def f1(): print "f1" f1=staticmethod(f1)
... K={"f1" : foo.f1, \ "f1" : foo.f2 \ }
The name 'foo' doesn't exist as a global variable
until after the class definition has been fully
executed. To make what you want work do
class foo:
def f1():
print "f1"
f1=staticmethod(f1)
def f2():
print "f2"
f2 = staticmethod(f2)
K={"f1" : f1,
"f2" : f2,
}
This works because the class definition creates
its own scope, and 'f1' and 'f2' are valid variables
in that scope.
NOTE: I removed the unneeded "\" characters for
stylistic reasons. If there's a "{" (or "(" or "[")
then the interpreter doesn't assume that a newline
means the end of the statement until after the
closing character.
The only time it's really needed is for the print
statement. In almost every other case you should
use some sort of parenthesis, brackets, etc. For
example, instead of
a = this_is_a_very_long_variable_name + \
and_here_is_another_long_name
you should use
a = (this_is_a_very_long_variable_name +
and_here_is_another_long_name)
Andrew da***@dalkescientific.com
Andrew Dalke wrote: Paulo da Silva wrote:
class foo: def f1(): print "f1" f1=staticmethod(f1)
...
K={"f1" : foo.f1, \ "f1" : foo.f2 \ }
The name 'foo' doesn't exist as a global variable until after the class definition has been fully executed. To make what you want work do
class foo: def f1(): print "f1" f1=staticmethod(f1)
def f2(): print "f2" f2 = staticmethod(f2)
K={"f1" : f1, "f2" : f2, }
This works because the class definition creates its own scope, and 'f1' and 'f2' are valid variables in that scope.
NOTE: I removed the unneeded "\" characters for stylistic reasons. If there's a "{" (or "(" or "[") then the interpreter doesn't assume that a newline means the end of the statement until after the closing character.
The only time it's really needed is for the print statement. In almost every other case you should use some sort of parenthesis, brackets, etc. For example, instead of
a = this_is_a_very_long_variable_name + \ and_here_is_another_long_name
you should use
a = (this_is_a_very_long_variable_name + and_here_is_another_long_name)
Andrew da***@dalkescientific.com
Yo Andrew. That doesn't work. Check my previous post w/ errors.
Richard Blackwood wrote: Yo Andrew. That doesn't work. Check my previous post w/ errors.
What do you mean?
Ahh, I see I solved the first problem (can't find 'foo')
without solving what the OP wanted. Try this reordering.
class foo:
def f1():
print "f1"
def f2():
print "f2"
K={"f1" : f1,
"f2" : f2,
}
f1 = staticmethod(f1)
f2 = staticmethod(f2)
def main():
foo.K["f1"]()
foo.K["f2"]()
if __name__ == "__main__":
main()
The 'staticmethod' is a descriptor and only works in
the context of a class.
Functions get turned into methods only in the context
of a class.
So to use a function as a function, get it before it
turns into a method or staticmethod.
Andrew da***@dalkescientific.com
<SNIP> class foo: def f1(): print "f1"
def f2(): print "f2"
K={"f1" : f1, "f2" : f2, } f1 = staticmethod(f1) f2 = staticmethod(f2)
def main(): foo.K["f1"]() foo.K["f2"]()
if __name__ == "__main__": main()
The 'staticmethod' is a descriptor and only works in the context of a class.
Functions get turned into methods only in the context of a class.
So to use a function as a function, get it before it turns into a method or staticmethod.
Andrew da***@dalkescientific.com
Ingenious solution Andrew! A true beauty.
On Sun, 10 Oct 2004 03:56:13 GMT, Andrew Dalke <ad****@mindspring.com> wrote: Richard Blackwood wrote: Yo Andrew. That doesn't work. Check my previous post w/ errors. What do you mean?
Ahh, I see I solved the first problem (can't find 'foo') without solving what the OP wanted. Try this reordering.
class foo: def f1(): print "f1"
def f2(): print "f2"
K={"f1" : f1, "f2" : f2, } f1 = staticmethod(f1) f2 = staticmethod(f2)
def main(): foo.K["f1"]() foo.K["f2"]()
if __name__ == "__main__": main()
The 'staticmethod' is a descriptor and only works in the context of a class.
Or where you force the issue as-if ;-) Functions get turned into methods only in the context of a class.
So to use a function as a function, get it before it turns into a method or staticmethod.
Or make a custom descriptor K that invokes the getattr magic as if getting foo.f1
of foo().f1, and thus letting the staticmethod descriptor deliver the function. This
lets you generalize K to handle other kinds of class attributes as-if also.
If you wanted to exclude all but certain names allowed by K[name], you could do
that in __getitem__ by raising KeyError for the others.
This is for educational purposes only, not a general recommendation ;-) class foo(object):
... def f1():
... print "f1"
... f1=staticmethod(f1)
... def f2():
... print "f2"
... f2 = staticmethod(f2)
... def f3(*args):
... print 'method f3', args
... def f4(*args):
... print 'class method f4', args
... f4 = classmethod(f4)
... f5 = property(lambda *args:('property f5', args))
... class K(object):
... def __get__(self, inst, cls=None):
... if inst is None: self.obj=cls
... else: self.obj = inst
... return self
... def __getitem__(self, key):
... return getattr(self.obj, key)
... K = K()
... foo.f1
<function f1 at 0x0090C730> foo.K['f1']
<function f1 at 0x0090C730> foo.f1()
f1 foo.K['f1']()
f1 foo.K['f2']()
f2 foo.f3
<unbound method foo.f3> foo.K['f3']
<unbound method foo.f3> foo.f3(foo())
method f3 (<__main__.foo object at 0x009015B0>,) foo.K['f3'](foo())
method f3 (<__main__.foo object at 0x009015B0>,) foo.f4
<bound method type.f4 of <class '__main__.foo'>> foo.K['f4']
<bound method type.f4 of <class '__main__.foo'>> foo.f4()
class method f4 (<class '__main__.foo'>,) foo.K['f4']()
class method f4 (<class '__main__.foo'>,) foo.f5
<property object at 0x0090E468> foo.K['f5']
<property object at 0x0090E468>
Ok, now via a foo instance: f = foo() f.f5
('property f5', (<__main__.foo object at 0x009015B0>,)) f.K['f5']
('property f5', (<__main__.foo object at 0x009015B0>,)) f.f1
<function f1 at 0x0090C730> f.K['f1']
<function f1 at 0x0090C730> f.K['f1']()
f1 f.f3
<bound method foo.f3 of <__main__.foo object at 0x009015B0>> f.f3()
method f3 (<__main__.foo object at 0x009015B0>,) f.K['f3']
<bound method foo.f3 of <__main__.foo object at 0x009015B0>> f.K['f3']()
method f3 (<__main__.foo object at 0x009015B0>,)
Reminder that via the class, it's unbound: foo.K['f3']
<unbound method foo.f3>
The class method is bound to the class instance either way f.f4
<bound method type.f4 of <class '__main__.foo'>> f.K['f4']
<bound method type.f4 of <class '__main__.foo'>> f.K['f4']()
class method f4 (<class '__main__.foo'>,)
foo.f4
<bound method type.f4 of <class '__main__.foo'>> foo.K['f4']
<bound method type.f4 of <class '__main__.foo'>> foo.K['f4']()
class method f4 (<class '__main__.foo'>,)
Regards,
Bengt Richter
Richard Blackwood wrote: Now that I think of it some more, why did you add that object arg? That's not necessary.
It gets you a new-style class instead of an old-style class, and it is a
good habit to have. http://www.python.org/2.2.3/descrintro.html
--
Michael Hoffman
On Sun, 10 Oct 2004 07:43:22 GMT, bo**@oz.net (Bengt Richter) wrote:
[...] Or make a custom descriptor K that invokes the getattr magic as if getting foo.f1 of foo().f1, and thus letting the staticmethod descriptor deliver the function. This
^^-- oops, typo: that "of" should be "or" ;-/
Regards,
Bengt Richter
Michael Hoffman wrote: Richard Blackwood wrote:
Now that I think of it some more, why did you add that object arg? That's not necessary.
It gets you a new-style class instead of an old-style class, and it is a good habit to have.
http://www.python.org/2.2.3/descrintro.html
Why a necessary good habit?
Richard Blackwood wrote: Michael Hoffman wrote: http://www.python.org/2.2.3/descrintro.html
Why a necessary good habit?
Feel free to read the web page I posted for all kinds of information
about new-style classes and why they are useful.
--
Michael Hoffman This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Lee Stewart |
last post by:
Another question about writing PHP 5 extensions. What's the difference in
PHP_MINIT() / PHP_MSHUTDOWN() and PHP_RINIT() / PHP_RSHUTDOWN()? When would
a "per request" init be made?
Thanks,...
|
by: FC |
last post by:
Hello all:
I am fairly new the Oracle and SQL and I am trying to find out how can I
achieve the following: I have a program that uses a database (schema for
Oracle?) and I am creating NEW tables...
|
by: Alexander van Doormalen |
last post by:
I have a situation that user controls are dynamically loaded within a
page. To know which control to 're-add' to the page I saved the control
path in the ViewState. This Control is added using...
|
by: Jess |
last post by:
Hello,
I tried several books to find out the details of object
initialization. Unfortunately, I'm still confused by two specific
concepts, namely default-initialization and...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
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
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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,...
|
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,...
| |