¿Cómo devolver un valor de init en Python?
Tengo una clase con una función __init__
.
¿Cómo puedo devolver un valor entero de esta función cuando se crea un objeto?
Escribí un programa, donde __init__
hace el análisis de la línea de comandos y necesito tener algún valor establecido. ¿Está bien configurarlo en variable global y usarlo en otras funciones miembro? Si es así, ¿cómo hacer eso? Hasta ahora, he declarado una variable fuera de clase. ¿y configurarlo una función no se refleja en otra función??
8 answers
__init__
es necesario devolver Ninguno. No puedes (o al menos no deberías) devolver algo más.
Intente hacer lo que quiera para devolver una variable de instancia (o función).
>>> class Foo:
... def __init__(self):
... return 42
...
>>> foo = Foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() should return None
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-18 08:48:32
¿Por qué querrías hacer eso?
Si desea devolver algún otro objeto cuando se llama a una clase, use el método __new__()
:
class MyClass(object):
def __init__(self):
print "never called in this case"
def __new__(cls):
return 42
obj = MyClass()
print obj
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 11:46:09
De la documentación de __init__
:
Como una restricción especial en los constructores, no se puede devolver ningún valor; al hacerlo, se generará un TypeError en tiempo de ejecución.
Como prueba, este código:
class Foo(object):
def __init__(self):
return 2
f = Foo()
Da este error:
Traceback (most recent call last):
File "test_init.py", line 5, in <module>
f = Foo()
TypeError: __init__() should return None, not 'int'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 11:41:16
Ejemplo de uso de la materia en cuestión puede ser como:
class SampleObject(object)
def __new__(cls,Item)
if self.IsValid(Item):
return super(SampleObject, cls).__new__(cls)
else:
return None
def __init__(self,Item)
self.InitData(Item) #large amount of data and very complex calculations
...
ValidObjects=[]
for i in data:
Item=SampleObject(i)
if Item: # in case the i data is valid for the sample object
ValidObjects.Append(Item)
No tengo suficiente reputación así que no puedo escribir un comentario, es una locura! Me gustaría poder publicar como un comentario a weronika
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:24
El método __init__
, al igual que otros métodos y funciones, devuelve None de forma predeterminada en ausencia de una instrucción return, por lo que puede escribirlo como cualquiera de estos:
class Foo:
def __init__(self):
self.value=42
class Bar:
def __init__(self):
self.value=42
return None
Pero, por supuesto, agregar el return None
no te compra nada.
No estoy seguro de lo que está buscando, pero podría estar interesado en uno de estos:
class Foo:
def __init__(self):
self.value=42
def __str__(self):
return str(self.value)
f=Foo()
print f.value
print f
Impresiones:
42
42
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 11:52:08
__init__
no devuelve nada y siempre debe devolver None
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 11:39:51
Solo quería agregar, puede devolver clases en __init__
@property
def failureException(self):
class MyCustomException(AssertionError):
def __init__(self_, *args, **kwargs):
*** Your code here ***
return super().__init__(*args, **kwargs)
MyCustomException.__name__ = AssertionError.__name__
return MyCustomException
El método anterior le ayuda a implementar una acción específica sobre una Excepción en su prueba
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-02 08:52:42
Bueno, si ya no le importa la instancia del objeto ... ¡puedes reemplazarlo!
class MuaHaHa():
def __init__(self, ret):
self=ret
print MuaHaHa('foo')=='foo'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-04 18:34:21