使用类对象作为字符串而不使用str()

时间:2017-06-26 19:37:10

标签: python string python-3.x

这种行为在Python中是否可行?

class A():
    def __init__(self, string):
        self.string = string
    def __???__(self):
        return self.string

a = A("world")
hw = "hello "+a
print(hw)
>>> hello world

我知道我可以做str(a),但我想知道是否可以使用'a'就好像它是一个字符串对象。

3 个答案:

答案 0 :(得分:2)

这样的事情怎么样?使用http://localhost:port/appArtefact/helloworld中的UserString

collections

https://repl.it/JClw/0

答案 1 :(得分:2)

这对我有用:

class A(str):

    def __init__(self, string):
        super().__init__()

a = A('world')
hw = 'hello ' + a
print(hw)

输出:

hello world

添加自定义函数进行测试:

class A(str):

     def __init__(self, string):
        self.string = string
        super().__init__()

    def custom_func(self, multiple):

        self = self.string * multiple
        return self

a = A('world')
hw = 'hello ' + a
print(hw)

new_a = a.custom_func(3)
print(new_a)

输出:

hello world
worldworldworld

或者,如果你不需要在启动课程时做任何事情:

class A(str):
    pass

    def custom_func(self, multiple):
        self = self * multiple
        return self

答案 2 :(得分:1)

做:

class A:
    def __init__(self, string):
        self.string = string

    # __add__: instance + noninstance
    #          instance + instance
    def __add__(self, string):
        print('__add__')
        return self.string + string

    # __radd__: noninstance + instance
    def __radd__(self, string):
        print('__radd__')
        return string + self.string


a = A("world")
hw = "hello " + a
print(1, hw)

hw = a + " hello"
print(2, hw)

hw = a + a
print(3, hw)

输出:

__radd__
(1, 'hello world')
__add__
(2, 'world hello')
__add__
__radd__
(3, 'worldworld')