Seite 1 von 1

unbound method

Verfasst: Samstag 30. Oktober 2004, 23:05
von murphy
[vielleicht nur eine blöde frage von einem anfänger]

ich habe wohl nicht verstanden, was "unbound methods" sind.

Code: Alles auswählen

class Foo:
	def __init__(self, name):
		self.name = name
	def think_unbound():
		print "I'm %s and I'm unbound :D yeah it's freedom man" % self.name
	def think(self):
		print "I'm %s and I'm bound :( *sniff*" % self.name
herby = Foo('Herby')
herby.think()  #-> I'm bound :( *sniff*
Foo.think_unbound()  #-> TypeError: unbound method think_unbound() must be called with Foo instance as first argument (got nothing instead)
Foo.think_unbound(herby) #-> TypeError: think_unbound() takes no arguments (1 given)
ich kriege einfach think_unbound() nicht aufgerufen.
wie geht das?

Verfasst: Samstag 30. Oktober 2004, 23:51
von Sorgenkind

Code: Alles auswählen

class Foo: 
    def __init__(self, name): 
        self.name = name
    @staticmethod
    def think_unbound(): 
        print "I'm unbound  yeah it's freedom man but i don't have access to an instance of Foo"
    def think(self): 
        print "I'm %s and I'm bound  *sniff*" % self.name
So in etwa... (Python 2.4)

in Python 2.3 gehts so:

Code: Alles auswählen

class Foo: 
    def __init__(self, name): 
        self.name = name
    def think_unbound(): 
        print "I'm unbound  yeah it's freedom man but i don't have access to an instance of Foo"
    think_unbound=staticmethod(think_unbound)
    def think(self): 
        print "I'm %s and I'm bound  *sniff*" % self.name

Verfasst: Samstag 30. Oktober 2004, 23:56
von Dookie
Hi murphy,

eventuell willst du eine staticmethod:

Code: Alles auswählen

class Foo:
    def __init__(self, name):
        self.name = name
    def think_unbound():
        print "I'm %s and I'm unbound Very Happy yeah it's freedom man" % self.name
    think_unbound = staticmethod(think_unbound)
    def think(self):
        print "I'm %s and I'm bound Sad *sniff*" % self.name
herby = Foo('Herby')
herby.think()  #-> I'm bound Sad *sniff*
Foo.think_unbound()  #-> TypeError: unbound method think_unbound() must be called with Foo instance as first argument (got nothing instead)
Foo.think_unbound(herby) #-> TypeError: think_unbound() takes no arguments (1 given)
gibt natürlich auch einen Fehler aus, da ja in einer static-methode kein self definiert ist und du nicht auf self.name zugreiffen kannst.


Gruß

Dookie

Verfasst: Sonntag 31. Oktober 2004, 00:04
von murphy
ok...aber was ist think_unbound ohne @staticmethod? was habe ich da geschrieben? eine mthode, die man nie aufrufen kann?

Verfasst: Sonntag 31. Oktober 2004, 00:11
von Dookie
murphy hat geschrieben:was habe ich da geschrieben?
Um ehrlich zu sein Misst ;)


Gruß

Dookie