How can I create a new string
object with Python __new__
method so that the string object should have class attributes also.
For example, I have tested this in 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()
Result : 'hai new obj. you are not string object. you are only cls object'
objA
Result : < main .A object at 0x22799710>
I have tested the same with PyNode class of (PyMel)
objB =PyNode('object01')
objB
Result : nt.Transform(u'object01')
But PyNode object is giving a unicode or string object. That means objB
can be used directly as string or unicode but objA
can't be used like that
How can I get something like objB
ouput?
Use
class A(str)
to make A
a subclass of 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.