Unbound Method Error
Chris Rebert
clp2 at rebertia.com
Mon Jun 8 22:30:22 EDT 2009
On Mon, Jun 8, 2009 at 7:23 PM, lczancanella<lczancanella at gmail.com> wrote:
> Hi, i am brand new in Python, so sorry if this question is too basic,
> but i have tried a lot and dont have success... I have the following
> code...
>
> class Funcoes:
> def CifradorDeCesar(mensagem, chave, funcao):
> mensagem_encriptada=''
> if funcao == 1:
> for byte in mensagem:
> if byte.isalpha():
> byte_encriptado=chr(ord(byte)+chave)
> if byte.isupper() and ord(byte_encriptado) > 90:
> byte_encriptado=chr(ord(byte_encriptado)-26)
> if byte.islower() and ord(byte_encriptado) > 122:
> byte_encriptado=chr(ord(byte_encriptado)-26)
> else:
> byte_encriptado=byte
> mensagem_encriptada+=byte_encriptado
> else:
> for byte in mensagem:
> if byte.isalpha():
> byte_encriptado=chr(ord(byte)-chave)
> if byte.isupper() and ord(byte_encriptado) < 65:
> byte_encriptado=chr(ord(byte_encriptado)+26)
> if byte.islower() and ord(byte_encriptado) < 97:
> byte_encriptado=chr(ord(byte_encriptado)+26)
> else:
> byte_encriptado=byte
> mensagem_encriptada+=byte_encriptado
>
> return mensagem_encriptada
>
> class MC(Funcoes, type):
> def __init__(cls, clsname, bases, ns):
> def addtrace(f):
> def t(self, *args, **kwargs):
> for att in self.__crypt__:
> atribcripto = getattr(self, att)
> atribdescripto = Funcoes.CifradorDeCesar
> (atribcripto, 3, 2)
> setattr(self, att, atribdescripto)
> ret = f(self, *args, **kwargs)
> for att in self.__crypt__:
> atribdescripto = getattr(self, att)
> atribcripto = Funcoes.CifradorDeCesar
> (atribdescripto, 3, 1)
> setattr(self, att, atribcripto)
> # aqui seta __signature__ vazio, assina e atribui
> __signature__
> return ret
> return t
> from types import FunctionType
> for name,obj in ns.items():
> if type(obj) == FunctionType:
> setattr(cls, name, addtrace(ns[name]))
>
> class C():
>
> __metaclass__ = MC
> __crypt__ = ["_a", "_b"]
>
> _a = 1
> _b = 2
>
> def add(self, a, b):
> _a = a
> _b = b
> return a+b
>
> then i call
>
>>>> i = C()
>>>> i.add(2,2)
>
> and the error:
>
> File "C:\Users\Junior\Desktop\Python\T2.py", line 37, in t
> atribdescripto = Funcoes.CifradorDeCesar(atribcripto, 3, 2)
> TypeError: unbound method CifradorDeCesar() must be called with
> Funcoes instance as first argument (got int instance instead)
`CifradorDeCesar` is an instance method of the class `Funcoes`, and
thus can only be used on instances of the class, *NOT the class
itself*.
Since it appears to be just a normal function (as suggested by the
name of the class and the fact that it lacks `self` as its first
parameter), you should scrap the class entirely and just define
`CifradorDeCesar` in the toplevel body of the module.
Unlike Java, it is *not* good Python style to unnecessarily cram
functions into classes.
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-list
mailing list