向类添加属性的更具Python风格的方法?
我正在处理来自两个不同网页的数据集,但对于同一个人,这些数据集是法律信息。有些数据在第一页上可用,因此我使用适当的信息初始化被告对象,并将当前没有数据的属性设置为向类添加属性的更具Python风格的方法?,python,python-2.7,oop,Python,Python 2.7,Oop,我正在处理来自两个不同网页的数据集,但对于同一个人,这些数据集是法律信息。有些数据在第一页上可用,因此我使用适当的信息初始化被告对象,并将当前没有数据的属性设置为null。这是一节课: class Defendant(object): """holds data for each individual defendant""" def __init__(self,full_name,first_name,last_name,type_of_appeal,county,case_n
null
。这是一节课:
class Defendant(object):
"""holds data for each individual defendant"""
def __init__(self,full_name,first_name,last_name,type_of_appeal,county,case_number,date_of_filing,
race,sex,dc_number,hair_color,eye_color,height,weight,birth_date,initial_receipt_date,current_facility,current_custody,current_release_date,link_to_page):
self.full_name = full_name
self.first_name = first_name
self.last_name = last_name
self.type_of_appeal = type_of_appeal
self.county = county
self.case_number = case_number
self.date_of_filing = date_of_filing
self.race = 'null'
self.sex = 'null'
self.dc_number = 'null'
self.hair_color = 'null'
self.eye_color = 'null'
self.height = 'null'
self.weight = 'null'
self.birth_date = 'null'
self.initial_receipt_date = 'null'
self.current_facility = 'null'
self.current_custody = 'null'
self.current_release_date = 'null'
self.link_to_page = link_to_page
这就是我在被告列表中添加一个半填的被告对象时的样子:
list_of_defendants.append(Defendant(name_final,'null','null',type_of_appeal_final,county_parsed_final,case_number,date_of_filing,'null','null','null','null','null','null','null','null','null','null','null','null',link_to_page))
然后,当我从另一个页面获取其余数据时,我将这些属性设置为null,如下所示:
for defendant in list_of_defendants:
defendant.sex = location_of_sex_on_page
defendant.first_name = location_of_first_name_on_page
## Etc.
我的问题是:当我只有一半的信息要存储在类对象中时,有没有一种更具python风格的方法来向类添加属性,或者有没有一种不那么丑陋的方法来初始化类对象?因此,有一个更简单的示例来说明如何做到:
class Foo:
def __init__(self, a, b, e, c=None, d=None):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
但是,如果您在需要实例化时从未拥有c
和d
,我建议您这样做:
class Foo:
def __init__(self, a, b, e):
self.a = a
self.b = b
self.c = None
self.d = None
self.e = e
编辑:另一种方法可以是:
class Defendant(object):
__attrs = (
'full_name',
'first_name',
'last_name',
'type_of_appeal',
'county',
'case_number',
'date_of_filing',
'race',
'sex',
'dc_number',
'hair_color',
'eye_color',
'height',
'weight',
'birth_date',
'initial_receipt_date',
'current_facility',
'current_custody',
'current_release_date',
'link_to_page'
)
def __update(self, *args, **kwargs):
self.__dict__.update(dict(zip(self.__attrs, args)))
self.__dict__.update(kwargs)
def __init__(self, *args, **kwargs):
self.__dict__ = dict.fromkeys(Defendant.__attrs, None)
self.__update(*args, **kwargs)
update_from_data = __update
if __name__ == '__main__':
test = Defendant('foo bar', 'foo', 'bar', height=180, weight=85)
test.update_from_data('Superman', 'Clark', 'Kent', hair_color='red', county='SmallVille')
首先,对设置为null的任何参数使用默认值。这样,在实例化对象时甚至不需要指定这些参数(并且可以使用参数名称以任何顺序指定确实需要的任何参数)。您应该使用Python值
None
,而不是字符串“null”
,除非有使用该字符串的特定原因。在Python2.x中,带有默认值的参数需要放在最后,因此link_to_page
需要移到这些参数之前
然后,您可以通过更新实例的\uuuu dict\uuu
属性来设置属性,该属性存储附加到实例的属性。每个参数都将设置为具有相同名称的实例的属性
def __init__(self, full_name, first_name, last_name, type_of_appeal, county, case_number,
date_of_filing, link_to_page, race=None, sex=None, dc_number=None,
hair_color=None, eye_color=None, height=None, weight=None, birth_date=None,
initial_receipt_date=None, current_facility=None, current_custody=None,
current_release_date=None):
# set all arguments as attributes of this instance
code = self.__init__.__func__.func_code
argnames = code.co_varnames[1:code.co_argcount]
locs = locals()
self.__dict__.update((name, locs[name]) for name in argnames)
您还可以考虑从两个其他名称参数合成
@property
def full_name(self):
return self.first_name + " " + self.last_name
对于更新,我会添加一个方法来完成,但只接受使用**
的关键字参数。为了帮助保护数据的完整性,我们将只更改已经存在且设置为None
的属性
def update(self, **kwargs):
self.__dict__.update((k, kwargs[k]) for k in kwargs
if self.__dict__.get(k, False) is None)
然后,您可以通过一次呼叫轻松更新所有您想要的:
defendant.update(eye_color="Brown", hair_color="Black", sex="Male")
要确保实例已完全填写,可以添加一个方法或属性,用于检查以确保所有属性都不是None
:
@property
def valid(self):
return all(self.__dict__[k] is not None for k in self.__dict__)
如果可以将每个属性作为名称-值对传入,可以使用以下方法:
class Defendant(object):
fields = ['full_name', 'first_name', 'last_name', 'type_of_appeal',
'county', 'case_number', 'date_of_filing', 'race', 'sex',
'dc_number', 'hair_color', 'eye_color', 'height', 'weight',
'birth_date', 'initial_receipt_date', 'current_facility',
'current_custody', 'current_release_date', 'link_to_page']
def __init__(self, **kwargs):
self.update(**kwargs)
def update(self, **kwargs):
self.__dict__.update(kwargs)
def blank_fields(self):
return [field for field in self.fields if field not in self.__dict__]
def verify(self):
blanks = self.blank_fields()
if blanks:
print 'The fields {} have not been set.'.format(', '.join(blanks))
return False
return True
defendant = Defendant(full_name='John Doe', first_name='John', last_name='Doe')
defendant.update(county='Here', height='5-11', birth_date='1000 BC')
defendant.verify()
# The fields type_of_appeal, case_number, date_of_filing, race... have not been set.
用法如下所示:
class Defendant(object):
fields = ['full_name', 'first_name', 'last_name', 'type_of_appeal',
'county', 'case_number', 'date_of_filing', 'race', 'sex',
'dc_number', 'hair_color', 'eye_color', 'height', 'weight',
'birth_date', 'initial_receipt_date', 'current_facility',
'current_custody', 'current_release_date', 'link_to_page']
def __init__(self, **kwargs):
self.update(**kwargs)
def update(self, **kwargs):
self.__dict__.update(kwargs)
def blank_fields(self):
return [field for field in self.fields if field not in self.__dict__]
def verify(self):
blanks = self.blank_fields()
if blanks:
print 'The fields {} have not been set.'.format(', '.join(blanks))
return False
return True
defendant = Defendant(full_name='John Doe', first_name='John', last_name='Doe')
defendant.update(county='Here', height='5-11', birth_date='1000 BC')
defendant.verify()
# The fields type_of_appeal, case_number, date_of_filing, race... have not been set.
将此扩展为使用必填字段和可选字段将很容易。或者,您可以向初始化添加必需的参数。或者,您可以检查以确保每个名称-值对都有一个有效的名称。等等…我想说,最具蟒蛇风格的方式是这样的:
class Defendant(Model):
full_name = None # Some default value
first_name = None
last_name = None
type_of_appeal = None
county = None
case_number = None
date_of_filing = None
race = None
sex = None
dc_number = None
hair_color = None
eye_color = None
height = None
weight = None
birth_date = None
initial_receipt_date = None
current_facility = None
current_custody = None
current_release_date = None
link_to_page = None
干净,一切只定义一次,并自动工作
关于模型
超级类。。。如果您使用的是像Django这样的web框架,请务必继承他们的模型,这样就完成了。它有你需要的所有线路
否则,要实现一些简短而甜蜜的东西,一个简单的方法是从以下继承您的类:
class Model(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
并根据可用字段进行实例化:
d1 = Defendant(height=1.75)
print d1.height
d2 = Defendant(full_name='Peter')
print d2.full_name
通过一些元编程,您可以实现许多更酷的事情,比如字段类型检查、值检查、重复声明等等。。如果您使用的是python 3,则可以轻松地允许通过args(基于声明顺序)或kwargs将值传递给\uuuu init\uuuu
方法。您可以将参数默认为'null'
,这样您就不需要在初始化时指定它们,您可以将最后一个值指定为link\u to\u page=link\u to\u page
,并跳过中间的所有值。空值在Python中表示为None
,而不是字符串'Null'
。请不要毫无根据地指责我。