Come sovraccaricare il metodo __init__ in base al tipo di argomento?
-
02-07-2019 - |
Domanda
Diciamo che ho una classe che ha un membro chiamato data che è un elenco.
Voglio essere in grado di inizializzare la classe con, ad esempio, un nome file (che contiene i dati per inizializzare l'elenco) o con un elenco effettivo.
Qual è la tua tecnica per farlo?
Basta controllare il tipo guardando __class__
?
C'è qualche trucco che potrei perdere?
Sono abituato al C ++ in cui il sovraccarico per tipo di argomento è facile.
Soluzione
Un modo molto più ordinato di ottenere "costruttori alternativi" è usare metodi di classe. Ad esempio:
>>> class MyData:
... def __init__(self, data):
... "Initialize MyData from a sequence"
... self.data = data
...
... @classmethod
... def fromfilename(cls, filename):
... "Initialize MyData from a file"
... data = open(filename).readlines()
... return cls(data)
...
... @classmethod
... def fromdict(cls, datadict):
... "Initialize MyData from a dict's items"
... return cls(datadict.items())
...
>>> MyData([1, 2, 3]).data
[1, 2, 3]
>>> MyData.fromfilename("/tmp/foobar").data
['foo\n', 'bar\n', 'baz\n']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]
Il motivo per cui è più ordinato è che non ci sono dubbi su quale tipo è previsto e non sei obbligato a indovinare cosa intendeva fare il chiamante con il tipo di dati che ti ha dato. Il problema con isinstance (x, basestring)
è che non c'è modo per il chiamante di dirti, ad esempio, che anche se il tipo non è un basestring, dovresti trattarlo come una stringa ( e non un'altra sequenza.) E forse il chiamante vorrebbe usare lo stesso tipo per scopi diversi, a volte come un singolo elemento e talvolta come una sequenza di elementi. Essere espliciti toglie ogni dubbio e porta a un codice più solido e più chiaro.
Altri suggerimenti
Ottima domanda. Ho anche affrontato questo problema, e mentre sono d'accordo che "fabbriche" (costruttori di metodi di classe) sono un buon metodo, vorrei suggerirne un altro, che ho anche trovato molto utile:
Ecco un esempio (questo è un metodo read
e non un costruttore, ma l'idea è la stessa):
def read(self, str=None, filename=None, addr=0):
""" Read binary data and return a store object. The data
store is also saved in the interal 'data' attribute.
The data can either be taken from a string (str
argument) or a file (provide a filename, which will
be read in binary mode). If both are provided, the str
will be used. If neither is provided, an ArgumentError
is raised.
"""
if str is None:
if filename is None:
raise ArgumentError('Please supply a string or a filename')
file = open(filename, 'rb')
str = file.read()
file.close()
...
... # rest of code
L'idea chiave è che sta usando l'eccellente supporto di Python per argomenti con nome per implementarlo. Ora, se voglio leggere i dati da un file, dico:
obj.read(filename="blob.txt")
E per leggerlo da una stringa, dico:
obj.read(str="\x34\x55")
In questo modo l'utente ha un solo metodo per chiamare. Gestirlo all'interno, come hai visto, non è eccessivamente complesso
Correzione rapida e sporca
class MyData:
def __init__(string=None,list=None):
if string is not None:
#do stuff
elif list is not None:
#do other stuff
else:
#make data empty
Quindi puoi chiamarlo con
MyData(astring)
MyData(None, alist)
MyData()
Un modo migliore sarebbe usare isinstance e la conversione del tipo. Se ti sto capendo bene, vuoi questo:
def __init__ (self, filename):
if isinstance (filename, basestring):
# filename is a string
else:
# try to convert to a list
self.path = list (filename)
con python3, puoi utilizzare Implementare Multiple Invio con annotazioni di funzioni come ha scritto Python Cookbook:
import time
class Date(metaclass=MultipleMeta):
def __init__(self, year:int, month:int, day:int):
self.year = year
self.month = month
self.day = day
def __init__(self):
t = time.localtime()
self.__init__(t.tm_year, t.tm_mon, t.tm_mday)
e funziona come:
>>> d = Date(2012, 12, 21)
>>> d.year
2012
>>> e = Date()
>>> e.year
2018
Dovresti usare isinstance
isinstance(...)
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
Probabilmente vuoi la funzione integrata isinstance
:
self.data = data if isinstance(data, list) else self.parse(data)
La mia soluzione preferita è:
class MyClass:
_data = []
__init__(self,data=None):
# do init stuff
if not data: return
self._data = list(data) # list() copies the list, instead of pointing to it.
Quindi invocalo con MyClass ()
o MyClass ([1,2,3])
.
Spero che sia d'aiuto. Buona programmazione!
OK, fantastico. Ho appena combinato questo esempio con una tupla, non un nome file, ma è facile. Grazie a tutti.
class MyData:
def __init__(self, data):
self.myList = []
if isinstance(data, tuple):
for i in data:
self.myList.append(i)
else:
self.myList = data
def GetData(self):
print self.myList
a = [1,2]
b = (2,3)
c = MyData (a)
d = MyData (b)
c.GetData ()
d.GetData ()
[1, 2]
[2, 3]
Perché non vai ancora più pitonico?
class AutoList:
def __init__(self, inp):
try: ## Assume an opened-file...
self.data = inp.read()
except AttributeError:
try: ## Assume an existent filename...
with open(inp, 'r') as fd:
self.data = fd.read()
except:
self.data = inp ## Who cares what that might be?