Ada*_*tan 5 python design-patterns overloading
我有一个概念性的Python设计困境.
假设我有一个City类,它代表数据库中的一个城市.该City对象可通过两种方式进行初始化:
name,country,population,...),这将在数据库中生成一个新的城市,并检索其ID.这意味着City对象将始终具有ID - 初始化ID或从数据库派生的新创建ID.
经典的Java方法会使构造函数重载 - 一个构造函数将获得一个int参数,另一个构造函数将获得许多强类型参数.
get_city_id,并从中获得CityFromID并
CityFromNewData从它,但是这是一个很大的努力来解决这个语言空白.使用**kargs似乎非常不优雅,因为构造函数的签名没有明确说明所需的输入参数,文档字符串是不够的:
class City(object):
def __init__(self, city_id=None, *args, **kargs):
try:
if city_id==None:
self.city_id=city_id
else:
self.city_name=kargs['name']
except:
error="A city object must be instanciated with a city id or with"+\
" full city details."
raise NameError(error)
Run Code Online (Sandbox Code Playgroud)
是否有一个Pythonic,优雅的构造函数重载解决方案?
亚当
怎么样:
class City(object):
def __init__(self, name, description, country, populations):
self.city_name = name
# etc.
@classmethod
def from_id(cls, city_id):
# initialise from DB
Run Code Online (Sandbox Code Playgroud)
然后你可以做普通的对象创建:
>>> c = City('Hollowberg', '', 'Densin', 3)
>>> c.id
1233L
>>> c2 = City.from_id(1233)
Run Code Online (Sandbox Code Playgroud)
~~~~~~
您也可以查看SQLAlchemy(和Elixir)以获得更好的方法来完成这些工作