麻烦继承str [英] trouble subclassing str

查看:117
本文介绍了麻烦继承str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想继承内置的str类型。例如:


-


class MyString(str):


def __init __( self,txt,data):

super(MyString,self).__ init __(txt)

self.data = data


如果__name__ ==''__ main__'':


s1 = MyString(" some text",100)


-


我收到错误:


Traceback(最近一次调用最后一次):

文件" MyString。 py",第27行,在?

s1 = MyString(" some text",12)

TypeError:str()最多需要1个参数(给定2个)


我在OS X上使用Python 2.3。想法?

I''d like to subclass the built-in str type. For example:

--

class MyString(str):

def __init__(self, txt, data):
super(MyString,self).__init__(txt)
self.data = data

if __name__ == ''__main__'':

s1 = MyString("some text", 100)

--

but I get the error:

Traceback (most recent call last):
File "MyString.py", line 27, in ?
s1 = MyString("some text", 12)
TypeError: str() takes at most 1 argument (2 given)

I am using Python 2.3 on OS X. Ideas?

推荐答案

我的第一个思想是确保子类化str确实是你想要做的b $ b b。这里是我有一个str子类的地方

真的是一种特殊的str:


类PaddedStr(str):

def __new __(cls,s,l,padc =''''):

如果l> len(s):

s2 ="%s%s" %(s,padc *(l-len(s)))

返回str .__ new __(str,s2)

else:

return str .__ new __(str,s)


print">%s<" %PaddedStr(" aaa",10)

print">%s<" %PaddedStr(aaa,8,。)

(当子类化str时,你必须从你的

子类中调用str .__ new__'' __new__方法,因为str'是不可变的。不要忘记

__new__需要第一个参数,这是输入类。我

想想我剩下的示例是非常明显的。)


但是如果你是str的子类只是为了你可以轻松打印你的

对象,那么看看实现__str__实例你的

班的方法。保留真实is-a的继承关系。通常,当设计师真正意味着拥有时,会错误地应用
继承。或者

is-implemented-using-a,在这些情况下,假定的超类

最好使用成员变量引用,并委托给它。 br />

- Paul

My first thought is "make sure that subclassing str is really what you
want to do." Here is a place where I have a subclass of str that
really is a special kind of str:

class PaddedStr(str):
def __new__(cls,s,l,padc='' ''):
if l > len(s):
s2 = "%s%s" % (s,padc*(l-len(s)))
return str.__new__(str,s2)
else:
return str.__new__(str,s)

print ">%s<" % PaddedStr("aaa",10)
print ">%s<" % PaddedStr("aaa",8,".")
(When subclassing str, you have to call str.__new__ from your
subclass''s __new__ method, since str''s are immutable. Don''t forget
that __new__ requires a first parameter which is the input class. I
think the rest of my example is pretty self-explanatory.)

But if you are subclassing str just so that you can easily print your
objects, look at implementing the __str__ instance method on your
class. Reserve inheritance for true "is-a" relationships. Often,
inheritance is misapplied when the designer really means "has-a" or
"is-implemented-using-a", and in these cases, the supposed superclass
is better referenced using a member variable, and delegating to it.

-- Paul


2005年6月23日星期四12:25:58 -0700,Paul McGuire写道:
On Thu, 23 Jun 2005 12:25:58 -0700, Paul McGuire wrote:
但是如果你是str的子类只是为了你可以轻松打印你的
对象,那么看看你的
类实现__str__实例方法。保留真实is-a的继承关系。通常,当设计师真正意味着拥有时,
继承被误用。或者
is-implemented-using-a,在这些情况下,使用成员变量更好地引用所谓的超类
,并委托给它。
But if you are subclassing str just so that you can easily print your
objects, look at implementing the __str__ instance method on your
class. Reserve inheritance for true "is-a" relationships. Often,
inheritance is misapplied when the designer really means "has-a" or
"is-implemented-using-a", and in these cases, the supposed superclass
is better referenced using a member variable, and delegating to it.




既然我们只是在谈论另一个话题中的流行语,而且自学成才的人知道他们是什么,我不会/>
假设有人想给出一个简单实用的例子,说明保罗的意思是什么?


我打算带一个在这里拼凑并猜测。 Paul没有创建子类

的str,而是建议你创建一个类:


class MyClass:

def __init __(self,value):

#value预计是一个字符串

self.value = self.mangle(value)

def mangle(self,s):

#在s上工作以确保它看起来像你想要的样子

return" ***" + s + ***"

def __str __(自我):

返回self.value


(仅限错误检查等)生产代码)。


然后就像这样使用它:


py> myprintablestr = MyClass(可爱的垃圾邮件!)

py>打印myprintablestr

***可爱的垃圾邮件!!! ***


我关闭了吗?

-

史蒂文



Since we''ve just be talking about buzzwords in another thread, and the
difficulty self-taught folks have in knowing what they are, I don''t
suppose somebody would like to give a simple, practical example of what
Paul means?

I''m going to take a punt here and guess. Instead of creating a sub-class
of str, Paul suggests you simply create a class:

class MyClass:
def __init__(self, value):
# value is expected to be a string
self.value = self.mangle(value)
def mangle(self, s):
# do work on s to make sure it looks the way you want it to look
return "*** " + s + " ***"
def __str__(self):
return self.value

(only with error checking etc for production code).

Then you use it like this:

py> myprintablestr = MyClass("Lovely Spam!")
py> print myprintablestr
*** Lovely Spam!!! ***

Am I close?
--
Steven


在文章< pa **************************** @ REMOVETHIScyber.co m.au>,

Steven D''Aprano< st *** @ REMOVETHIScyber.com.au>写道:
In article <pa****************************@REMOVETHIScyber.co m.au>,
Steven D''Aprano <st***@REMOVETHIScyber.com.au> wrote:
2005年6月23日星期四12:25:58 -0700,Paul McGuire写道:
On Thu, 23 Jun 2005 12:25:58 -0700, Paul McGuire wrote:
但是如果你是继承str的话只是为了让你可以轻松打印你的
对象,看看你的
类实现__str__实例方法。保留真实is-a的继承关系。通常,当设计师真正意味着拥有时,
继承被误用。或者
is-implemented-using-a,在这些情况下,使用成员变量更好地引用所谓的超类
,并委托给它。
But if you are subclassing str just so that you can easily print your
objects, look at implementing the __str__ instance method on your
class. Reserve inheritance for true "is-a" relationships. Often,
inheritance is misapplied when the designer really means "has-a" or
"is-implemented-using-a", and in these cases, the supposed superclass
is better referenced using a member variable, and delegating to it.


<由于我们只是在谈论另一个话题中的流行语,以及自学成才的人在知道它们是什么的困难,我不会想有人想要给保罗意味着什么的一个简单实用的例子?

我打算在这里采取行动并猜测。 Paul没有创建str的子类,而是建议你简单地创建一个类:

类MyClass:
def __init __(self,value):
#值预计是一个字符串
self.value = self.mangle(value)
def mangle(self,s):
#做s工作以确保它看起来像你的方式希望它看起来像
返回*** + s + ***
def __str __(自我):
返回self.value

(仅对生产代码进行错误检查等)。

然后你就像这样使用它:

py> myprintablestr = MyClass(可爱的垃圾邮件!)
py>打印myprintablestr
***可爱的垃圾邮件!!! ***

我关闭了吗?



Since we''ve just be talking about buzzwords in another thread, and the
difficulty self-taught folks have in knowing what they are, I don''t
suppose somebody would like to give a simple, practical example of what
Paul means?

I''m going to take a punt here and guess. Instead of creating a sub-class
of str, Paul suggests you simply create a class:

class MyClass:
def __init__(self, value):
# value is expected to be a string
self.value = self.mangle(value)
def mangle(self, s):
# do work on s to make sure it looks the way you want it to look
return "*** " + s + " ***"
def __str__(self):
return self.value

(only with error checking etc for production code).

Then you use it like this:

py> myprintablestr = MyClass("Lovely Spam!")
py> print myprintablestr
*** Lovely Spam!!! ***

Am I close?




这就是我读它的方式,值作为您委派给的成员变量



留下无法解释的是真实是-a关系。声音

就像一个隐含的矛盾 - 你不能实现

真正的东西。如果没有这个,并且

可能会更加细致地替换is-implemented-using-a,

我不知道你怎么能真正确定关键点。


Donn Cave, do**@u.washington.edu


这篇关于麻烦继承str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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