- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个类 (Rectangle
),它实现了一个方法 (describe
),如下所示:
class Rectangle(object):
def __init__(self, height, width):
self.height = height
self.width = width
def describe(self):
return 'Rectangle with height {:0.2f} and width {:0.2f}'.format(float(self.height),
float(self.width))
这按预期工作:
r = Rectangle(5, 3)
r.describe()
>>> 'Rectangle with height 5.00 and width 3.00'
我希望能够在实例化时指定一个替代函数来代替describe
。我相信以下方法有效:
import functools as ft
class RectangleEnhanced(object):
def __init__(self, height, width, description_function=None):
self.height = height
self.width = width
if description_function is None:
self.describe = self.default_describe
else:
self.describe = ft.partial(description_function, self)
def default_describe(self):
return 'Rectangle with height {:0.2f} and width {:0.2f}'.format(float(self.height),
float(self.width))
这样:
s = RectangleEnhanced(5, 3)
s.describe()
>>> 'Rectangle with height 5.00 and width 3.00'
继续像以前一样工作,但是,此外:
def area_description(enh_rect):
return 'Rectangle with area {:0.2f}'.format(float(enh_rect.height * enh_rect.width))
t = RectangleEnhanced(5, 3, area_description)
t.describe()
>>> 'Rectangle with area 15.00'
这是解决这个问题的合理方法吗?我无法想象我是第一个想要这样做的人,所以我很紧张下面的方法是次优的/非Pythonic的/坏的/等等。有“正确”的方法来处理这个问题吗?
<小时/>编辑
这是一个更接近我的用例的示例:
class FilterableCollection(object):
def __init__(self, items, owner, purpose, filterfunc=None):
self.items = set(items)
self.owner = owner
self.purpose = purpose
if filterfunc is None:
self.filterfunc = lambda x: True
else:
self.filterfunc = ft.partial(filterfunc, self)
def filtered(self):
return filter(self.filterfunc, self.items)
items = ['fun_ball', 'boring_ball', 'fun_bear', 'boring_bear']
owner = 'Bill'
purpose = 'fun'
f = FilterableCollection(items, owner, purpose)
print f.filtered()
def is_applicable(self, item):
return self.purpose in item
g = FilterableCollection(items, owner, purpose, is_applicable)
print g.filtered()
返回:
['fun_bear', 'fun_ball', 'boring_ball', 'boring_bear']
['fun_bear', 'fun_ball']
正如预期的那样。因此,我们的想法是,当您创建
FilterableCollection
的特定实例时,您可以创建一个自定义过滤器(这可能取决于该特定
FitlerableCollection
的其他属性),然后该过滤器可用随时被调用。因此可能有 10 个
FilterableCollections
float ,并且可以通过调用
.filtered
方法使用各自的过滤器对它们进行过滤。
我对通过继承或任何其他技术来实现这一点的想法持非常开放的态度。但在这种情况下这将如何应用呢?
最佳答案
The essence is that for each instance of the class, I want to be able to perform a certain kind of filtering on some data attached to the instance. Depending on the context, the kind of filtering required could vary widely.
您在此处描述的内容被称为 strategy pattern ,并且您的示例实现几乎尽可能Pythonic - Python函数是对象,在大多数主流语言中,相当多需要完整的“仿函数”类的设计模式都是用Python中的普通函数实现的。
我能看到的唯一“改进”是摆脱部分 - Python 函数确实知道如何成为实例方法:
if description_function is None:
self.describe = self.default_describe
else:
self.describe = description_function.__get__(self)
您可以阅读此内容以了解有关此行为的更多信息:https://wiki.python.org/moin/FromFunctionToMethod
这并不是说这会改变纯粹的功能(没有双关语),但它肯定会让你看起来像一个 PythonGuru(tm)
关于python - 通过接受替换函数作为参数,允许在 __init__ 期间重写对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33923003/
为什么正是是 A.__init__() B.__init__() D.__init__() 由以下代码打印?特别是: 为什么是C.__init__() 未打印? 为什么是C.__init__()如果我
目前我有这样的事情: @dataclass(frozen=True) class MyClass: a: str b: str c: str d: Dict[str, str] ...
我正在尝试从父类继承属性: class Human: def __init__(self,name,date_of_birth,gender,nationality): self.name =
如何扩展基类的 __init__,添加更多要解析的参数,而不需要 super().__init__(foo, bar) 在每个派生类中? class Ipsum: """ A base ips
这是我试图解决的一个非常简单的例子: class Test(object): some_dict = {Test: True} 问题是我无法在 Test 仍在定义时引用它 通常,我会这样做:
我在 Objective-C 中使用过这个结构: - (void)init { if (self = [super init]) { // init class }
我有一个类层次结构,其中 class Base 中的 __init__ 执行一些预初始化,然后调用方法 calculate。 calculate 方法在 class Base 中定义,但预计会在派生类
这是我在多种语言中都怀念的一个特性,想知道是否有人知道如何在 Python 中完成它。 我的想法是我有一个基类: class Base(object): def __init__(self):
我正在对 threading.Thread 类进行子类化,它目前看起来像这样: class MyThread(threading.Thread): def __init__(self:
我正在用 cython 写一些代码,我有一些 "Packages “within” modules" . — 这实际上是对我在那里的问题的跟进,结构应该是一样的。问题是这是 cython,所以我处理的
class AppendiveDict(c.OrderedDict): def __init__(self,func,*args): c.OrderedDict.__init_
看完this回答,我明白 __init__ 之外的变量由类的所有实例和 __init__ 内的变量共享每个实例都是唯一的。 我想使用所有实例共享的变量,随机给我的类实例一个唯一的参数。这是我尝试过的较
在下面的代码中: import tkinter as tk class CardShuffling(tk.Tk): background_colour = '#D3D3D3'
我正在覆盖类的 __new__() 方法以返回具有特定 __init__() 集的类实例。 Python 似乎调用类提供的 __init__() 方法而不是特定于实例的方法,尽管 Python 文档在
从内置类型和其他类派生时,内置类型的构造函数似乎没有调用父类(super class)构造函数。这会导致 __init__ 方法不会被 MRO 中内置函数之后的类型调用。 例子: class A:
答: super( BasicElement, self ).__init__() 乙: super( BasicElement, self ).__init__( self ) A 和 B 有什么区
class A(object): def __init__(self): print('A.__init__()') class D(A): def __init__(
到目前为止我已经成功地做了什么: 我创建了一个 elem 类来表示 html 元素(div、html、span、body 等)。 我可以像这样派生这个类来为每个元素创建子类: class elem:
我一直在努力理解 super() 在多重继承的上下文中的行为。我很困惑为什么在 test2.py 的父类中调用 super() 会导致为父类调用 __init__()? test1.py #!/usr
为什么我在 Python 代码中看不到以下内容? class A: def __init__(self, ...): # something important class B
我是一名优秀的程序员,十分优秀!