- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
在 Python 中有没有一种方法,可以让多个构造函数或多个方法具有相同的名称,它们接受的参数数量不同,或者一个或多个参数的类型?
如果不是,处理这种情况的最佳方法是什么?
举个例子,我编了一个颜色类。 这门课应该只是作为一个基本的例子来讨论这个问题,里面有很多不必要和/或多余的东西。
如果我可以用不同的对象(一个列表、另一个颜色对象或三个整数......)调用构造函数并且构造函数相应地处理它们,那就太好了。在这个基本示例中,它在某些情况下适用于 * args 和 * * kwargs,但使用类方法是我想出的唯一通用方法。什么是“最佳实践”之类的解决方案?
撇开构造函数不谈,如果我也想实现一个 _ add _ _ 方法,我怎样才能让这个方法接受所有这些:一个普通整数(添加到所有值)、三个整数(其中第一个与红色值相加等)或另一个颜色对象(其中两个红色值相加等)?
编辑
我添加了一个替代构造函数(初始化器,_ _ init _ _),它基本上可以完成我想要的所有工作。
但我坚持使用第一个方法和工厂方法。看起来更清楚了。
我还添加了 _ _ add _ _,它完成了上述所有操作,但我不确定它是否是好的样式。我尝试使用迭代协议(protocol)并退回到“单值模式”而不是检查特定类型。也许仍然很丑。
我看过_ _ 新 _ _,感谢您提供链接。
我的第一次快速尝试失败了:我从 * args 和 * * kwargs(它是一个类、一个列表等)中过滤 rgb 值,然后调用父类(super class)的 _ _ new _ _正确的参数(只是 r、g、b)将其传递给 init。对“Super(cls, self)._ _ new _ _ (....)”的调用有效,但由于我生成并返回与我调用的对象相同的对象(按预期),所有原始参数被传递给 _ _ init _ _(按预期工作),所以它保释了。
我可以完全摆脱 _ _ init _ _ 并在 _ _ new _ _ 中设置值,但我不知道...感觉我在滥用这里的东西 ;-) 我我想应该先仔细看看元类和新的。
来源:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Color (object):
# It's strict on what to accept, but I kinda like it that way.
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
# Maybe this would be a better __init__?
# The first may be more clear but this could handle way more cases...
# I like the first more though. What do you think?
#
#def __init__(self, obj):
# self.r, self.g, self.b = list(obj)[:3]
# This methods allows to use lists longer than 3 items (eg. rgba), where
# 'Color(*alist)' would bail
@classmethod
def from_List(cls, alist):
r, g, b = alist[:3]
return cls(r, g, b)
# So we could use dicts with more keys than rgb keys, where
# 'Color(**adict)' would bail
@classmethod
def from_Dict(cls, adict):
return cls(adict['r'], adict['g'], adict['b'])
# This should theoreticaly work with every object that's iterable.
# Maybe that's more intuitive duck typing than to rely on an object
# to have an as_List() methode or similar.
@classmethod
def from_Object(cls, obj):
return cls.from_List(list(obj))
def __str__(self):
return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b)
def _set_rgb(self, r, g, b):
self.r = r
self.g = g
self.b = b
def _get_rgb(self):
return (self.r, self.g, self.b)
rgb = property(_get_rgb, _set_rgb)
def as_List(self):
return [self.r, self.g, self.b]
def __iter__(self):
return (c for c in (self.r, self.g, self.b))
# We could add a single value (to all colorvalues) or a list of three
# (or more) values (from any object supporting the iterator protocoll)
# one for each colorvalue
def __add__(self, obj):
r, g, b = self.r, self.g, self.b
try:
ra, ga, ba = list(obj)[:3]
except TypeError:
ra = ga = ba = obj
r += ra
g += ga
b += ba
return Color(*Color.check_rgb(r, g, b))
@staticmethod
def check_rgb(*vals):
ret = []
for c in vals:
c = int(c)
c = min(c, 255)
c = max(c, 0)
ret.append(c)
return ret
class ColorAlpha(Color):
def __init__(self, r=0, g=0, b=0, alpha=255):
Color.__init__(self, r, g, b)
self.alpha = alpha
def __str__(self):
return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha)
# ...
if __name__ == '__main__':
l = (220, 0, 70)
la = (57, 58, 61, 255)
d = {'r': 220, 'g': 0, 'b':70}
da = {'r': 57, 'g': 58, 'b':61, 'a':255}
c = Color(); print c # <Color(0, 0, 0)>
ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)>
print '---'
c = Color(220, 0, 70); print c # <Color(220, 0, 70)>
c = Color(*l); print c # <Color(220, 0, 70)>
#c = Color(*la); print c # -> Fail
c = Color(**d); print c # <Color(220, 0, 70)>
#c = Color(**da); print c # -> Fail
print '---'
c = Color.from_Object(c); print c # <Color(220, 0, 70)>
c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)>
c = Color.from_List(l); print c # <Color(220, 0, 70)>
c = Color.from_List(la); print c # <Color(57, 58, 61, 255)>
c = Color.from_Dict(d); print c # <Color(220, 0, 70)>
c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)>
print '---'
print 'Check =', Color.check_rgb('1', 0x29a, -23, 40)
# Check = [1, 255, 0, 40]
print '%s + %s = %s' % (c, 10, c + 10)
# <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)>
print '%s + %s = %s' % (c, ca, c + ca)
# <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)>
最佳答案
你可以有工厂方法,这很好。但为什么不按原样调用它呢?
Color(r, g, b)
Color(*[r, g, b])
Color(**{'r': r, 'g': g, 'b': b})
这是 python 的方式。至于 from object 构造函数,我更喜欢这样的东西:
Color(*Color2.as_list())
显式优于隐式 - Python Zen
关于python - 如何在 Python 中处理具有不同参数集(或类型)的构造函数或方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/356718/
我有 table 像这样 -------------------------------------------- id size title priority
我的应用在不同的 Activity (4 个 Activity )中仅包含横幅广告。所以我的疑问是, 我可以对所有横幅广告使用一个广告单元 ID 吗? 或者 每个 Activity 使用不同的广告单元
我有任意(但统一)数字列表的任意列表。 (它们是 n 空间中 bin 的边界坐标,我想绘制其角,但这并不重要。)我想生成所有可能组合的列表。所以:[[1,2], [3,4],[5,6]] 产生 [[1
我刚刚在学校开始学习 Java,正在尝试自定义控件和图形。我目前正在研究图案锁,一开始一切都很好,但突然间它绘制不正确。我确实更改了一些代码,但是当我看到错误时,我立即将其更改回来(撤消,ftw),但
在获取 Distinct 的 Count 时,我在使用 Group By With Rollup 时遇到了一个小问题。 问题是 Rollup 摘要只是所有分组中 Distinct 值的总数,而不是所有
这不起作用: select count(distinct colA, colB) from mytable 我知道我可以通过双选来简单地解决这个问题。 select count(*) from (
这个问题在这里已经有了答案: JavaScript regex whitespace characters (5 个回答) 2年前关闭。 你能解释一下为什么我会得到 false比较 text ===
这个问题已经有答案了: 奥 git _a (56 个回答) 已关闭 9 年前。 我被要求用 Javascript 编写一个函数 sortByFoo 来正确响应此测试: // Does not cras
所以,我不得不说,SQL 是迄今为止我作为开发人员最薄弱的一面。也许我想要完成的事情很简单。我有这样的东西(这不是真正的模型,但为了使其易于理解而不浪费太多时间解释它,我想出了一个完全模仿我必须使用的
这个问题在这里已经有了答案: How does the "this" keyword work? (22 个回答) 3年前关闭。 简而言之:为什么在使用 Objects 时,直接调用的函数和通过引用传
这个问题在这里已经有了答案: 关闭 12 年前。 Possible Duplicate: what is the difference between (.) dot operator and (-
我真的不明白这里发生了什么但是: 当我这样做时: colorIndex += len - stopPos; for(int m = 0; m < len - stopPos; m++) { c
思考 MySQL 中的 Group By 函数的最佳方式是什么? 我正在编写一个 MySQL 查询,通过 ODBC 连接在 Excel 的数据透视表中提取数据,以便用户可以轻松访问数据。 例如,我有:
我想要的SQL是这样的: SELECT week_no, type, SELECT count(distinct user_id) FROM group WHERE pts > 0 FROM bas
商店表: +--+-------+--------+ |id|name |date | +--+-------+--------+ |1 |x |Ma
对于 chrome 和 ff,当涉及到可怕的 ie 时,这个脚本工作完美。有问题 function getY(oElement) { var curtop = 0; if (oElem
我现在无法提供代码,因为我目前正在脑海中研究这个想法并在互联网上四处乱逛。 我了解了进程间通信和使用共享内存在进程之间共享数据(特别是结构)。 但是,在对保存在不同 .c 文件中的程序使用 fork(
我想在用户集合中使用不同的功能。在 mongo shell 中,我可以像下面这样使用: db.users.distinct("name"); 其中名称是用于区分的集合字段。 同样我想要,在 C
List nastava_izvjestaj = new List(); var data_context = new DataEvidencijaDataContext();
我的 Rails 应用程序中有 Ransack 搜索和 Foundation,本地 css 渲染正常,而生产中的同一个应用程序有一个怪癖: 应用程序中的其他内容完全相同。 我在 Chrome 和 Sa
我是一名优秀的程序员,十分优秀!