Is Python strongly typed?

2019-01-01 09:58发布

I've come across links that say Python is a strongly typed language.

However, I thought in strongly typed languages you couldn't do this :

bob = 1
bob = "bob"

I thought a strongly typed language didn't accept type-changing at run-time. Maybe I've got a wrong (or too simplist) definition of strong/weak types.

So, is Python a strongly or weakly typed language?

10条回答
弹指情弦暗扣
2楼-- · 2019-01-01 10:29

TLDR;

Python's typing is Dynamic so you can change an int variable to a string

x = 'somestring'
x = 50

Python typing is Strong so you can't merge types:

'x' + 3 --> TypeError: cannot concatenate 'str' and 'int' objects

In weakly-typed Javascript this happens...

 'x'+3 = 'x3'

Regarding Type Inference

Java forces you to explicitly declare your object types

int x = 50

Kotlin uses inference to realize it's an int

x = 50

But because both languages use static types, x can't be changed from an int. Neither language would allow a dynamic change like

x = 50
x = 'now a string'
查看更多
怪性笑人.
3楼-- · 2019-01-01 10:30

According to this wiki Python article Python is both dynamically and strongly typed (provides a good explanation too).

Perhaps you are thinking about statically typed languages where types can not change during program execution and type checking occurs during compile time to detect possible errors.

This SO question might be of interest: Dynamic type languages versus static type languages and this Wikipedia article on Type Systems provides more information

查看更多
低头抚发
4楼-- · 2019-01-01 10:30

The term "strong typing" does not have a definite definition.

Therefore, the use of the term depends on with whom you're speaking.

I do not consider any language, in which the type of a variable is not either explicitly declared, or statically typed to be strongly typed.

Strong typing doesn't just preclude conversion (for example, "automatically" converting from an integer to a string). It precludes assignment (i.e., changing the type of a variable).

If the following code compiles (interprets), the language is not strong-typed:

Foo = 1 Foo = "1"

In a strongly typed language, a programmer can "count on" a type.

For example, if a programmer sees the declaration,

UINT64 kZarkCount;

and he or she knows that 20 lines later, kZarkCount is still a UINT64 (as long as it occurs in the same block) - without having to examine intervening code.

查看更多
春风洒进眼中
5楼-- · 2019-01-01 10:34

i think, this simple example should you explain the diffs between strong and dynamic typing:

>>> tup = ('1', 1, .1)
>>> for item in tup:
...     type(item)
...
<type 'str'>
<type 'int'>
<type 'float'>
>>>

java:

public static void main(String[] args) {
        int i = 1;
        i = "1"; //will be error
        i = '0.1'; // will be error
    }
查看更多
登录 后发表回答