How to inject attributes of an object in python by calling a method in the __init__ method?
As a simple example, let's say we want to create many instances Earthquake
that have the attributes of the coordinates of name, start time and hycocenter coming from other sources, encoded as strings ( "Nepal 25-4-2015T11:56:26 28.14 84.71 15.0"
).
class Earthquake(object):
def __init__(self, strline):
....
So, we need to do the following:
-
parse the string to get name, date, time, latitude, longitude and depth.
-
enter
Earthquake
by passing these values ββto the initialization call__init__
.
Imagine the first part is done with a simple function:
import datetime as dt
def myfunc(strline):
items = line.split()
name = items[0]
otime = dt.datetime.strptime(items[1], "%d-%m-%YT%H:%M:%S")
lat, lon, depth = map(float, items[2:])
Now I want to use a class class Earthquake
to create objects Earthquake
so that each object has attributes Earthquake.name
, Earthquake.otime
, Earthquake.lat
, Earthquake.lon
and Earthquake.depth
.
How can I call a method myfunc
in a method __init__
in a class to initialize an object with the above attributes?
source to share
I would do it quite the opposite. Parsing this line is obviously part of the object Earthquake
, so provide it as an alternative constructor using a class method:
class Earthquake(object):
def __init__(self, name, otime, lat, lon, depth):
self.name = name
self.otime = otime
self.lat = lat
self.lon = lon
self.depth = depth
@classmethod
def from_string(cls, strline):
items = line.split()
name = items[0]
otime = dt.datetime.strptime(items[1], "%d-%m-%YT%H:%M:%S")
lat, lon, depth = map(float, items[2:])
return cls(name, otime, lat, lon, depth)
Now you call for example:
quake = Earthquake.from_string("Nepal 25-4-2015T11:56:26 28.14 84.71 15.0")
Or, if you want the function to remain self-contained, add to it return
:
def myfunc(strline):
...
return name, otime, lat, lon, depth
and call the class method:
class Earthquake(object):
...
@classmethod
def from_string(cls, strline):
return cls(*myfunc(strline))
(if this syntax is unimportant, see What does ** (double star) and * (star) do for parameters? )
source to share
One of the things you can do is call Earthquake with a string as a parameter, and in that __init__
you call the parse function.
import datetime as dt
class Earthquake(object):
def __init__(self, strline):
self.parse_data(strline)
def parse_data(self, strline):
items = line.split()
self.name = items[0]
self.otime = dt.datetime.strptime(items[1], "%d-%m-%YT%H:%M:%S")
self.lat, self.lon, self.depth = map(float, items[2:])
source to share