eag*_*arn 1 python java string string-concatenation strong-typing
我熟悉强弱类型.我也知道Java是强类型的.现在我学习python,它是一种强大的类型语言.但现在我看到python比Java更"强"类型.举例说明
public class StringConcat {
public static void main(String[] args) {
String s="hello ";
s+=4;
System.out.println(s);
}
}
Run Code Online (Sandbox Code Playgroud)
没有错误并打印你好4
在python中
>>> x="hello"
>>> x+=4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
Run Code Online (Sandbox Code Playgroud)
所以这个例子演示了python是强类型的.除非Java引擎盖下,做一些操作将int转换为String并执行String concat.
尽管你的例子,Java仍然是强类型的.代码相当于
String s = "hello ";
s = s + 4;
Run Code Online (Sandbox Code Playgroud)
并且Java会将其转换4
为字符串,然后执行字符串连接.这是一种语言功能.
但是,在Python中,您不能使用+
连接4
到您的字符串,因为该语言不会自由地将其转换为str
.正如您所指出的,Java会为您做到这一点.
归档时间: |
|
查看次数: |
655 次 |
最近记录: |