Why can't I "string" .print ()?

My understanding of print() in Python and Ruby (and other languages) is that it is a method for string (or other types). Since this syntax is so often used:

type hello

work.

So why doesn't "hi".print() in Python or "hi".print in Ruby?

+7
source share
7 answers

When you do something like "hi".print() , you mean that the string object "hi" has a print method. This is not the case. Instead, print is a function that takes a string (or other types) as input.

+9
source

Ruby has an Object#display method ( doc here ) that sends the representation of the object to the current output stream or to one specified as an argument.

(I find it difficult to work with irb if I use ; at the end of the line, to suppress the print of the return value, if I do this, the display output is not displayed, even if I flush the stream.)

+4
source

Why is this needed? String classes rarely have void print methods - and you'll never need them, because the standard static print function can print these lines anyway. It is important to note: method(someObject) not necessarily the same as someObject.method() .

+2
source

This is not a string method. Before Python 3, it was a statement. (like break or import ), and you could use both print "hi" and print("hi") . From Python 3, this is replaced by a function so you can no longer use print "hi" :

Printing is a feature

The print statement has been replaced by print () with keyword arguments to replace most of the special syntax of the old print statement (PEP 3105).

+2
source

What do you suggest str.print should do?

print to stdout? how about stderr? or file? or serial port?

Printing on stdout is really a special case, but it is so ubiquitous that it can sometimes be missed.

Then we need to indicate where str should print every time we create a string?

At least we have to say

 "foo".print(sys.stdout) 

Hope this looks awful too. This is a confusion of responsibility.

+2
source

print not a string method in Python (or in Ruby, I believe). This is a statement (in Python 3 it is a global function). What for? First, not all you can print is a string. How about print 2 ?

0
source

If you are happier using a method rather than an instruction in Ruby, you can use the method mapping ( "test".display ) to achieve this or define a new method that is easily similar

 class String def print puts self end end 

and use it like this:

 "test".print 
-one
source

All Articles