i want to do
class foo(): # this class doesn't return and create object (object) , only runs main function when is called
@classmethod
def main(cls):
print "main function is called with using foo()"
foo()
# output #
# main function is called with using foo()
is there a way to do this ?
Moderator snippsat: Fixed code tag look at BBcode help
>>> class foo:
... def say(self):
... print("Hello!")
>>> bar = foo()
>>> bar.say()
Hello!
>>> say = bar.say
>>> say()
Hello!
You could rewrite
__new__()
to "forbid" creation of an object and to do some action, but why would someone sane want to do it ...
In [1]: class foo:
...: def __new__(cls):
...: print("foo")
...:
In [2]: foo()
foo
works with new style class (inherits from object)
>>> class foo(object):
... def __new__(cls):
... print "foo"
...
>>> foo()
foo
@
zivoni, thanks very very much. it works
(Mar-23-2017, 06:05 PM)harun2525 Wrote: [ -> ]@zivoni, thanks very very much. it works
But still... why? Is there any real use for that, aside from making other people reading your code hate you?
(Mar-23-2017, 06:26 PM)nilamo Wrote: [ -> ] (Mar-23-2017, 06:05 PM)harun2525 Wrote: [ -> ]@zivoni, thanks very very much. it works
But still... why? Is there any real use for that, aside from making other people reading your code hate you?
class clsOrHide(object):
def __new__(cls, widget, name):
cls.main(widget, name)
@staticmethod
def main(widget, name):
if name == "__main__":
gtk.main_quit()
else:
widget.hide()
return True
@classmethod
def del_event(cls, *args):
cls.main(args[0], args[-1] )
or
def clsOrHide(widget, name):
if name == "__main__":
gtk.main_quit()
else:
widget.hide()
return True
clsOrHide.del_event = lambda *args: clsOrHide(args[0], args[-1] )
which one is the better readable ?, which one has the better code view ?
Edit:
sometime, we can't know what will need
Neither are readable. It looks a little bit like an event handler that gets called multiple times for different reasons, which is... insane
Classes shouldn't execute anything other than initialization code.
If you create methods that run main, and you instantiate two of these
classes what happens?