1

文字列オブジェクトにもクラス属性が必要になるように、stringPythonメソッドで新しいオブジェクトを作成するにはどうすればよいですか。__new__

たとえば、Maya でこれをテストしました。

class A(object):
    def __new__(str, *args, **kwargs):
        return super(A, str).__new__(str)

    def __init__(self, obj):         
        self.obj =str(obj)

    def hai(self):
        print 'hai new obj. you are not string object. you are only cls object'

objA =A('object01')

objA.hai()

結果: 'こんにちは、新しい obj. あなたは文字列オブジェクトではありません。あなたはただのclsオブジェクトです'

objA

結果: < 0x22799710のメイン.A オブジェクト>

(PyMel)のPyNodeクラスで同じことをテストしました

objB =PyNode('object01')
objB

結果: nt.Transform(u'object01')

しかし、PyNode オブジェクトは unicode または string オブジェクトを提供しています。つまりobjB、文字列またはユニコードとして直接使用できますが、objAそのようには使用できません

出力のようなものを取得するにはどうすればよいobjBですか?

4

1 に答える 1

3

使用する

class A(str)

Aのサブクラスを作成するにはstr:

class A(str):
    def __new__(cls, *args, **kwargs):
        return super(A, cls).__new__(cls, *args, **kwargs)

    def hai(self):
        print('hai new obj. you are not string object. you are only cls object')

objA =A('object01')

objA.hai()
assert isinstance(objA, str)
于 2012-10-07T11:44:17.423 に答える