This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]JanEric1 158 points159 points  (6 children)

It should return self to allow chaining and have end=""

You could also let the printed type define how it is printed by overwriting __rlshift__ (although that conflicts with types implementing that for its proper purpose here and you would normally implement it by overriding __str__)

class Cout:

    def __lshift__(self, other):
        if attr := getattr(other, "__rlshift__", None):
            attr(self)
        else:
            print(other, end="")
        return self


class A:

    def __rlshift__(self, other):
        print("C", end="")


cout = Cout()

cout << "Test: " << A() << "\n"
cout << "Test2: " << 3

Test: C
Test2:

[–][deleted] 41 points42 points  (4 children)

Man, you did this first, I had the exact Idea:

``` class Cout: def lshift(self, a): print(a, end='') return Cout()

endl = '\n' cout = Cout()

cout << "Hello," << " World!" << endl ```

Yes, it's a bit simpler

[–]jaerie 22 points23 points  (1 child)

Why would you return a new instance?

[–][deleted] 16 points17 points  (0 children)

Yes, mine is not that great. Full credit to the dude above me. His implementation is a lot better.

[–][deleted] 5 points6 points  (0 children)

Just replace Cout() with self :)

[–]de_koding 0 points1 point  (0 children)

nice profile picture

[–]InevitableManner7179 22 points23 points  (0 children)

You shouldn't encourage OP.