gpt4 book ai didi

python - 我怎样才能简单地从现有实例继承方法?

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:15 26 4
gpt4 key购买 nike

下面我有一个非常简单的例子来说明我正在尝试做什么。我希望能够将 HTMLDecorator 与任何其他类一起使用。忽略它叫做 decorator 的事实,它只是一个名称。

import cgi

class ClassX(object):
pass # ... with own __repr__

class ClassY(object):
pass # ... with own __repr__

inst_x=ClassX()

inst_y=ClassY()

inst_z=[ i*i for i in range(25) ]

inst_b=True

class HTMLDecorator(object):
def html(self): # an "enhanced" version of __repr__
return cgi.escape(self.__repr__()).join(("<H1>","</H1>"))

print HTMLDecorator(inst_x).html()
print HTMLDecorator(inst_y).html()
wrapped_z = HTMLDecorator(inst_z)
inst_z[0] += 70
wrapped_z[0] += 71
print wrapped_z.html()
print HTMLDecorator(inst_b).html()

输出:

Traceback (most recent call last):  File "html.py", line 21, in     print HTMLDecorator(inst_x).html()TypeError: default __new__ takes no parameters

我想做的事情可行吗?如果是这样,我做错了什么?

最佳答案

Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.

看起来您正在尝试设置某种代理对象方案。这是可行的,并且有比您同事的解决方案更好的解决方案,但首先要考虑仅修补一些额外的方法是否会更容易。这不适用于像 bool 这样的内置类,但它适用于您的用户定义类:

def HTMLDecorator (obj):
def html ():
sep = cgi.escape (repr (obj))
return sep.join (("<H1>", "</H1>"))
obj.html = html
return obj

这是代理版本:

class HTMLDecorator(object):
def __init__ (self, wrapped):
self.__wrapped = wrapped

def html (self):
sep = cgi.escape (repr (self.__wrapped))
return sep.join (("<H1>", "</H1>"))

def __getattr__ (self, name):
return getattr (self.__wrapped, name)

def __setattr__ (self, name, value):
if not name.startswith ('_HTMLDecorator__'):
setattr (self.__wrapped, name, value)
return
super (HTMLDecorator, self).__setattr__ (name, value)

def __delattr__ (self, name):
delattr (self.__wraped, name)

关于python - 我怎样才能简单地从现有实例继承方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com