本文介绍了子类化内置类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道python不允许扩展像

str类这样的内置对象;但是你可以使用一个同名的类对它们进行子类化和

因此影响它们以获得相同的一般效果(虽然你必须使用

显式构造函数而不是文字)。


class str(str):

def display(self):

print self

str(''blah'')。display()


我只是在玩耍并意识到要分配给

__builtins __。str(或者如果你更喜欢sys.modules [''__ builtin __'']。str)

效果相同。


class mystr(str):

def display(self):

print self

__builtins __。str = mystr

str(''blah'')。显示()


所以这让我想知道......不能python(理论上)允许文字

使用扩展类__builtins中的对象__。< classas

文字的类?默认情况下,它将是标准基类,

但它也可以是自定义子类。那可能/轻松/

值得吗?


问候,

乔丹

I know that python doesn''t allow extending built-in objects like the
str class; but you can subclass them using a class of the same name and
thus shadow them to get the same general effect (albeit you have to use
the explicit constructor rather than literals).

class str(str):
def display(self):
print self
str(''blah'').display()

I was just playing around and realized that assigning to
__builtins__.str (or if you prefer sys.modules[''__builtin__''].str) has
the same effect.

class mystr(str):
def display(self):
print self
__builtins__.str = mystr
str(''blah'').display()

So that made me wonder...couldn''t python (in theory) allow for literals
to use extended classes by using the object in __builtins__.<classas
the class for literals? By default it would be the standard base class,
but it could also be a custom subclass. Would that be possible / easy /
worthwhile to do?

Regards,
Jordan

推荐答案



不幸的是文字代码生成时会解释文字,
$ b在编译程序可用之前$ b,你对

__builtns__的修改还没有完成,所以答案是不,我很害怕。


问候

Steve

-

Steve Holden +44 150 684 7255 +1 800 494 3119

Holden Web LLC / Ltd

Skype:holdenweb

最近的Ramblings

Unfortunately the literals are interpreted during bytecode generation,
before the compiled program is available, and your modifications to
__builtns__ haven''t been made, so the answer is "no", I''m afraid.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden




啊!那讲得通。我想这样做的唯一方法就是在每个对象上添加一个

的额外位来指示它是否构造了

字面意思然后在编译后重新初始化对象如果那个

位被设置。出于某种原因,我只是觉得这不会发生。 ;)


感谢您花时间解释。


问候,

Jordan

Ah! That makes sense. I guess the only way to do it would be to add an
extra bit to every object to indicate whether it was constructed
literally and then re-initialize the object after compilation if that
bit is set. For some reason I just don''t think that''s gonna happen. ;)

Thanks for taking the time to explain.

Regards,
Jordan




但是什么阻止将文字解释为对__builtins__对象的调用以及

函数?优化?还有什么?


-

_____________


Maric Michaud

_____________


亚里士多德 -

3 place des tapis

69004里昂

电话:+33 426 880 097

But what prevents to interpret literals as a call to __builtins__ objects and
functions ? optimization ? what else ?

--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097


这篇关于子类化内置类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:20