我想我理解强类型,但每次我查找弱类型的例子时,我最终会找到编程语言的例子,这些语言只是自动强制/转换类型.
例如,在本文中名为Typing:Strong vs. Weak,Static vs. Dynamic表示Python是强类型的,因为如果你试图:
蟒蛇
1 + "1"
Traceback (most recent call last):
File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Run Code Online (Sandbox Code Playgroud)
但是,在Java和C#中这样的事情是可能的,我们并不认为它们只是因为弱类型.
Java的
int a = 10;
String b = "b";
String result = a + b;
System.out.println(result);
Run Code Online (Sandbox Code Playgroud)
C#
int a = 10;
string b = "b";
string c = a + b;
Console.WriteLine(c);
Run Code Online (Sandbox Code Playgroud)
在另一篇名为Weakly Type Languages的文章中,作者说Perl是弱类型的,因为我可以将字符串连接到数字而反之亦然,而不进行任何显式转换.
Perl的
$a=10;
$b="a";
$c=$a.$b;
print $c; #10a
Run Code Online (Sandbox Code Playgroud)
所以同样的例子使得Perl弱类型,但不是Java和C#? …
在尝试编写一个模糊的,模糊的类型检查器时,发现了一种不可接受的代码模式.但是,它不一致地无法正常工作.这是最初用于测试它的代码.
def statictypes(a):
def b(a, b, c):
if b in a and not isinstance(c, a[b]): raise TypeError('{} should be {}, not {}'.format(b, a[b], type(c)))
return c
return __import__('functools').wraps(a)(lambda *c: b(a.__annotations__, 'return', a(*(b(a.__annotations__, *d) for d in zip(a.__code__.co_varnames, c)))))
@statictypes
def isallinstance(iterable: object, class_or_type_or_tuple: (type, tuple)) -> bool:
"""isallinstance(iterable, class_or_type_or_tuple) -> bool
Return whether all items in an iterable are instances of a class or of a
subclass thereof. With a type as second argument, return whether that is
all items' …Run Code Online (Sandbox Code Playgroud) 我开始学习Python,作为主要的Java开发人员,我遇到的最大问题是何时何时不使用类型检查.大多数人似乎都在说Python代码不需要进行类型检查,但是在我认为有必要时会有很多情况.例如,假设我需要使用方法参数来执行算术运算,为什么我不确定参数是数值数据类型?
此问题不仅限于功能.对于类变量,我也会遇到同样的思考过程.我应该或不应该使用属性(使用@property)来检查类型而不是定期实现的类变量?
这是一种为我开展发展的新方式,所以我很感激帮助理解.