删除继承(装饰模式?) [英] Removing inheritance (decorator pattern ?)

查看:62
本文介绍了删除继承(装饰模式?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,可以使用几个

正交选项自定义一个类。目前这是通过(多个)

继承来实现的,但这会导致子类的组合爆炸,因为

添加了更多的正交特征。当然,想到装饰模式

[1](不要混淆

术语装饰者的Python含义)。


然而,有一个扭曲。在标准装饰器模式中,

装饰器接受要装饰的对象并添加额外的

功能或通过覆盖一个或
来修改对象的行为
更多方法。它不会影响对象的创建方式,它按原样使用

。我的多重继承类虽然扮演双重角色:

不仅覆盖了一个或多个常规方法,而且它们可能也会覆盖__init__。这是一个玩具示例:


class Joinable(object):

def __init __(self,words):

self .__ words = list(words)

def join(self,delim ='',''):

return delim.join(self .__ words)


class Sorted(Joinable):

def __init __(self,words):

super(排序,自我).__ init __(排序(单词) ))

def join(self,delim ='',''):

return''[Sorted]%s''%super(Sorted,self)。加入(delim)


类反转(可加入):

def __init __(自我,单词):

super(反转,自我).__ init __(反向(单词))

def join(self,delim ='',''):

return''[Reversed]%s'' %super(Reversed,self).join(delim)


class SortedReversed(Sorted,Reversed):

pass


class ReversedSorted(Reversed,Sorted):

pass


if __name__ ==''__ main__'':

words =''这是一个te st''。split()

print SortedReversed(words).join()

print ReversedSorted(words).join()

所以我想知道,这里的装饰模式是否合适?如果是的话,

怎么样?如果没有,是否有另一种方法将继承转换为

委托?


George

[1] http://en.wikipedia.org/wiki/Decorator_pattern

I have a situation where one class can be customized with several
orthogonal options. Currently this is implemented with (multiple)
inheritance but this leads to combinatorial explosion of subclasses as
more orthogonal features are added. Naturally, the decorator pattern
[1] comes to mind (not to be confused with the the Python meaning of
the term "decorator").

However, there is a twist. In the standard decorator pattern, the
decorator accepts the object to be decorated and adds extra
functionality or modifies the object''s behavior by overriding one or
more methods. It does not affect how the object is created, it takes
it as is. My multiple inheritance classes though play a double role:
not only they override one or more regular methods, but they may
override __init__ as well. Here''s a toy example:

class Joinable(object):
def __init__(self, words):
self.__words = list(words)
def join(self, delim='',''):
return delim.join(self.__words)

class Sorted(Joinable):
def __init__(self, words):
super(Sorted,self).__init__(sorted(words))
def join(self, delim='',''):
return ''[Sorted] %s'' % super(Sorted,self).join(delim)

class Reversed(Joinable):
def __init__(self, words):
super(Reversed,self).__init__(reversed(words))
def join(self, delim='',''):
return ''[Reversed] %s'' % super(Reversed,self).join(delim)

class SortedReversed(Sorted, Reversed):
pass

class ReversedSorted(Reversed, Sorted):
pass

if __name__ == ''__main__'':
words = ''this is a test''.split()
print SortedReversed(words).join()
print ReversedSorted(words).join()
So I''m wondering, is the decorator pattern applicable here ? If yes,
how ? If not, is there another way to convert inheritance to
delegation ?

George
[1] http://en.wikipedia.org/wiki/Decorator_pattern

推荐答案

George Sakkis schrieb:
George Sakkis schrieb:

我的情况是一个班级可以定制几个

正交选项。目前这是通过(多个)

继承来实现的,但这会导致子类的组合爆炸,因为

添加了更多的正交特征。当然,想到装饰模式

[1](不要混淆

术语装饰者的Python含义)。


然而,有一个扭曲。在标准装饰器模式中,

装饰器接受要装饰的对象并添加额外的

功能或通过覆盖一个或
来修改对象的行为
更多方法。它不会影响对象的创建方式,它按原样使用

。我的多重继承类虽然扮演双重角色:

不仅覆盖了一个或多个常规方法,而且它们可能也会覆盖__init__。这是一个玩具示例:


class Joinable(object):

def __init __(self,words):

self .__ words = list(words)

def join(self,delim ='',''):

return delim.join(self .__ words)


class Sorted(Joinable):

def __init __(self,words):

super(排序,自我).__ init __(排序(单词) ))

def join(self,delim ='',''):

return''[Sorted]%s''%super(Sorted,self)。加入(delim)


类反转(可加入):

def __init __(自我,单词):

super(反转,自我).__ init __(反向(单词))

def join(self,delim ='',''):

return''[Reversed]%s'' %super(Reversed,self).join(delim)


class SortedReversed(Sorted,Reversed):

pass


class ReversedSorted(Reversed,Sorted):

pass


if __name__ ==''__ main__'':

words =''这是一个测试''。split()

print SortedReversed(words).join()

打印ReversedSorted(单词).join()


所以我想知道,装饰模式是否适用于此?如果是的话,

怎么样?如果没有,是否有另一种方法将继承转换为

委托?
I have a situation where one class can be customized with several
orthogonal options. Currently this is implemented with (multiple)
inheritance but this leads to combinatorial explosion of subclasses as
more orthogonal features are added. Naturally, the decorator pattern
[1] comes to mind (not to be confused with the the Python meaning of
the term "decorator").

However, there is a twist. In the standard decorator pattern, the
decorator accepts the object to be decorated and adds extra
functionality or modifies the object''s behavior by overriding one or
more methods. It does not affect how the object is created, it takes
it as is. My multiple inheritance classes though play a double role:
not only they override one or more regular methods, but they may
override __init__ as well. Here''s a toy example:

class Joinable(object):
def __init__(self, words):
self.__words = list(words)
def join(self, delim='',''):
return delim.join(self.__words)

class Sorted(Joinable):
def __init__(self, words):
super(Sorted,self).__init__(sorted(words))
def join(self, delim='',''):
return ''[Sorted] %s'' % super(Sorted,self).join(delim)

class Reversed(Joinable):
def __init__(self, words):
super(Reversed,self).__init__(reversed(words))
def join(self, delim='',''):
return ''[Reversed] %s'' % super(Reversed,self).join(delim)

class SortedReversed(Sorted, Reversed):
pass

class ReversedSorted(Reversed, Sorted):
pass

if __name__ == ''__main__'':
words = ''this is a test''.split()
print SortedReversed(words).join()
print ReversedSorted(words).join()
So I''m wondering, is the decorator pattern applicable here ? If yes,
how ? If not, is there another way to convert inheritance to
delegation ?



工厂 - 和动态子类化,如下所示:


随机导入


A级(对象):

通过


B级(对象):

通过

def create_instance():

superclasses = tuple(random.sample([A,B],random.randint(1,2)))

class BaseCombiner(类型):


def __new __(mcs,name,bases,d):

bases = superclasses + bases

返回类型(名称,基数,d)


类Foo(对象):

__metaclass__ = BaseCombiner

返回Foo()

$ x $ b for _ in xrange(10):

f = create_instance()

print f .__ class __.__ bases__


Diez

Factory - and dynamic subclassing, as shown here:

import random

class A(object):
pass

class B(object):
pass
def create_instance():
superclasses = tuple(random.sample([A, B], random.randint(1, 2)))
class BaseCombiner(type):

def __new__(mcs, name, bases, d):
bases = superclasses + bases
return type(name, bases, d)

class Foo(object):
__metaclass__ = BaseCombiner
return Foo()

for _ in xrange(10):
f = create_instance()
print f.__class__.__bases__

Diez




" George Sakkis" < ge *********** @ gmail.com写信息

新闻:a3 ******************* *************** @ k37g2000 hsf.googlegroups.com ...

|我的情况是一个班级可以定制几个

|正交选项。目前这是用(多个)

|实现的继承,但这导致子类的组合爆炸为

|添加了更多正交特征。当然,装饰图案

| [1]浮现在脑海中(不要混淆

|术语装饰者)的Python含义。

|

| [1] http://en.wikipedia.org/wiki/Decorator_pattern


我读了文章的第一部分。以下

"当有几种独立的

方式扩展功能时,这种差异变得最为重要。在一些面向对象的编程中,b / b $ b语言无法在运行时创建类,并且通常不能预测
设计时间。这意味着必须为每个可能的组合制作一个新的课程。


告诉我,Python中不需要这种模式。所有用户

类是在运行时创建的。可以使用

''extensions''参数定义一个类工厂,该参数创建一个类并根据扩展名添加方法。例如,人们甚至可以从

__init__的基本文本开始,根据扩展添加行,编译定义,

并添加* that *。甚至可以为

..__ name__属性生成特定值。


如果一般组中的实例具有不同的

__class__属性,可以考虑使用所有方法的主类

和只添加所需数据属性的init函数

(borderwidth,scroller state,等等。


我没有仔细阅读你的玩具示例,看看它是如何与

维基文章相关联的。

tjr


"George Sakkis" <ge***********@gmail.comwrote in message
news:a3**********************************@k37g2000 hsf.googlegroups.com...
|I have a situation where one class can be customized with several
| orthogonal options. Currently this is implemented with (multiple)
| inheritance but this leads to combinatorial explosion of subclasses as
| more orthogonal features are added. Naturally, the decorator pattern
| [1] comes to mind (not to be confused with the the Python meaning of
| the term "decorator").
|
| [1] http://en.wikipedia.org/wiki/Decorator_pattern

I read the first part of the article. The following
"This difference becomes most important when there are several independent
ways of extending functionality. In some object-oriented programming
languages, classes cannot be created at runtime, and it is typically not
possible to predict what combinations of extensions will be needed at
design time. This would mean that a new class would have to be made for
every possible combination"

suggests to me that this pattern is not needed in Python, where all user
classes are created at runtime. One can define a class factory with an
''extensions'' parameter that creates a class and adds methods according to
the extensions. One could even, for instance, start with a basic text for
__init__, add lines according to the extensions, compile the definition,
and add *that*. One could even generate a particularized value for the
..__name__ attribute.

If it is not important that instances in the general group have different
__class__ attributes, one might consider a master class with all methods
and an init function that only adds the data attributes needed
(borderwidth, scroller state, etc.).

I did not read your toy example enough to quite see how it connected to the
wiki article.

tjr


Diez B. Roggisch写道:
Diez B. Roggisch wrote:

George Sakkis schrieb :
George Sakkis schrieb:

>我的情况是可以使用几个
正交选项自定义一个类。目前,这是通过(多个)继承来实现的,但这会导致子类的组合爆炸,因为添加了更多的正交特征。当然,想到装饰模式[1](不要与术语装饰者的Python含义相混淆)。

但是,有扭曲。在标准装饰器模式中,
装饰器接受要装饰的对象并添加额外的功能或通过覆盖一个或多个方法来修改对象的行为。它不会影响对象的创建方式,而是按原样使用它。我的多重继承类虽然扮演双重角色:
不仅覆盖了一个或多个常规方法,而且它们也可以覆盖__init__。这是一个玩具示例:

类Joinable(对象):
def __init __(self,words):
self .__ words = list(words)
def join(self,delim ='',''):
返回delim.join(self .__ words)

class Sorted(Joinable):
def __init __(self,words ):
super(排序,自我).__ init __(排序(单词))
def join(self,delim ='',''):
return''[Sorted]%s ''%super(Sorted,self).join(delim)

类Reversed(Joinable):
def __init __(self,words):
super(Reversed,self) .__ init __(反向(单词))
def join(self,delim ='',''):
return''[Reversed]%s''%super(Reversed,self).join( delim)

class SortedReversed(Sorted,Reversed):
传递

类ReversedSorted(Reversed,Sorted):
传递

if __name__ ==''__ main__'':
words =''这是一个测试''.split()
print SortedReversed(w ords).join()
print ReversedSorted(words).join()

所以我想知道,装饰模式是否适用于此?如果是的话,
怎么样?如果没有,是否有另一种方法将继承转换为
委托?
>I have a situation where one class can be customized with several
orthogonal options. Currently this is implemented with (multiple)
inheritance but this leads to combinatorial explosion of subclasses as
more orthogonal features are added. Naturally, the decorator pattern
[1] comes to mind (not to be confused with the the Python meaning of
the term "decorator").

However, there is a twist. In the standard decorator pattern, the
decorator accepts the object to be decorated and adds extra
functionality or modifies the object''s behavior by overriding one or
more methods. It does not affect how the object is created, it takes
it as is. My multiple inheritance classes though play a double role:
not only they override one or more regular methods, but they may
override __init__ as well. Here''s a toy example:

class Joinable(object):
def __init__(self, words):
self.__words = list(words)
def join(self, delim='',''):
return delim.join(self.__words)

class Sorted(Joinable):
def __init__(self, words):
super(Sorted,self).__init__(sorted(words))
def join(self, delim='',''):
return ''[Sorted] %s'' % super(Sorted,self).join(delim)

class Reversed(Joinable):
def __init__(self, words):
super(Reversed,self).__init__(reversed(words))
def join(self, delim='',''):
return ''[Reversed] %s'' % super(Reversed,self).join(delim)

class SortedReversed(Sorted, Reversed):
pass

class ReversedSorted(Reversed, Sorted):
pass

if __name__ == ''__main__'':
words = ''this is a test''.split()
print SortedReversed(words).join()
print ReversedSorted(words).join()
So I''m wondering, is the decorator pattern applicable here ? If yes,
how ? If not, is there another way to convert inheritance to
delegation ?



工厂 - 和动态子类化,如下所示:


随机导入


A级(对象):

通过


B级(对象):

通过


def create_instance():

superclasses = tuple(random.sample([A,B],random.randint(1,2)))

类BaseCombiner(类型):


def __new __(mcs,name,bases,d):

bases = superclasses + bases

返回类型(名称,基数,d)


类Foo(对象):

__metaclass__ = BaseCombiner

返回Foo ()

$ x $ b for xrange(10):

f = create_instance()

print f .__ class __.__ bases__


Factory - and dynamic subclassing, as shown here:

import random

class A(object):
pass

class B(object):
pass
def create_instance():
superclasses = tuple(random.sample([A, B], random.randint(1, 2)))
class BaseCombiner(type):

def __new__(mcs, name, bases, d):
bases = superclasses + bases
return type(name, bases, d)

class Foo(object):
__metaclass__ = BaseCombiner
return Foo()

for _ in xrange(10):
f = create_instance()
print f.__class__.__bases__



现在我看到我当然可以放弃自己整个

__metaclass __- business并直接使用type()......哦,但至少它是
工作:)


Diez

Right now I see of course that I could have spared myself the whole
__metaclass__-business and directly used type()... Oh well, but at least it
worked :)

Diez


这篇关于删除继承(装饰模式?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆