简体   繁体   English

如何通过调用__init__方法中的方法在python中引入对象的属性?

[英]How to introduce the attributes of an object in python by calling a method in __init__ method?

As a simple example, let's assume that we want to create a lot of Earthquake instances, having name, origin time, and hypocenter coordinate attributes coming from other sources encoded as strings ( "Nepal 25-4-2015T11:56:26 28.14 84.71 15.0" ). 举个简单的例子,让我们假设我们要创建许多Earthquake实例,其名称,原点时间和震源坐标属性来自编码为字符串的其他来源( "Nepal 25-4-2015T11:56:26 28.14 84.71 15.0" )。

class Earthquake(object):
    def __init__(self, strline):
        ....

So, what we must do is: 所以,我们必须做的是:

  1. parse the string to receive name, date, time, latitude, longitude and depth. 解析字符串以接收名称,日期,时间,纬度,经度和深度。

  2. instantiate Earthquake by passing those values to initialization call __init__ . 通过将这些值传递给初始化调用__init__来实例化Earthquake

Imagine the first part is done by 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 the class class Earthquake to create Earthquake objects in a way that each object has attributes Earthquake.name , Earthquake.otime , Earthquake.lat , Earthquake.lon and Earthquake.depth . 现在我想使用class Earthquake来创建Earthquake对象,每个对象都有属性Earthquake.nameEarthquake.otimeEarthquake.latEarthquake.lonEarthquake.depth

How can I call myfunc method in __init__ method in a class to initialize an object with above attributes? 如何在类的__init__方法中调用myfunc方法来初始化具有上述属性的对象?

I would do that completely the other way around. 我会完全反过来这样做。 Parsing that string is clearly part of what an Earthquake object should do, so provide it as an alternate constructor using a class method : 解析该字符串显然是Earthquake对象应该做的事情的一部分,因此使用类方法将其作为备用构造函数提供:

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 eg: 现在你打电话给:

quake = Earthquake.from_string("Nepal 25-4-2015T11:56:26 28.14 84.71 15.0")

Or, if you want the function to remain standalone, add a return to it: 或者,如果您希望该函数保持独立,请添加一个return

def myfunc(strline):
    ...
    return name, otime, lat, lon, depth

and make the class method call it: 并使类方法调用它:

class Earthquake(object):

    ...

    @classmethod
    def from_string(cls, strline):
        return cls(*myfunc(strline))

(if this syntax is unfamiliar, see What does ** (double star) and * (star) do for parameters? ) (如果不熟悉这种语法,请参阅**(双星)和*(星)对参数做什么?

One of the things you could do is call Earthquake with the string as a parameter and on __init__ you call the parsing function. 您可以做的事情之一是使用字符串作为参数调用Earthquake,并在__init__调用解析函数。

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:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM