使变量的type()信息不变

时间:2019-01-18 12:01:15

标签: python

在python中,当我使用以下代码初始化x时:

x: int = 42
print(type(x)) # prints <class 'int'>

我想防止:

x = "omg" # should raise "TypeError: x is not of type str" or similar.
x: str = "omg" # should raise "TypeError: x is already defined" or similar.

换句话说,我想要在语言中添加一些可选的类型安全性和声明。这可能吗?是否有关于PEP的讨论?是否存在可以进行其他类型检查的语言工具或编译器标志?

2 个答案:

答案 0 :(得分:3)

PEP 484's "Non Goals" section明确表示:

  

还应该强调的是, Python仍将是一种动态类型化的语言,并且即使按照约定,作者也不希望使类型提示成为强制性的。

作为一种动态类型化的语言,类型信息的“真相来源”将始终是名称所指向的对象的运行时(动态)类型。名称本身(在这种情况下为 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_content_pop_up); imageUrl=new ArrayList<>(); for(int i=1;i<=3;i++) { imageUrl.add("https://www.gstatic.com/webp/gallery3/"+i+".png"); } LinearLayoutManager layoutManager=new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false); recyclerImagevIew=(RecyclerView)findViewById(R.id.image_recycler_view); recyclerImagevIew.setLayoutManager(layoutManager); ImagePopupAdapter imagePopupAdapter =new ImagePopupAdapter(this,imageUrl); recyclerImagevIew.setAdapter(imagePopupAdapter); background_Image=(ImageView) findViewById(R.id.background_image); cross_sign =(TextView)findViewById(R.id.cross_button); cross_sign.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); // StartAsyncTask(); // StartTimer(); handler=new Handler(); runnable= new Runnable() { @Override public void run() { if(index<imageUrl.size()) { Glide.with(getApplicationContext()).load(imageUrl.get(index)).into(background_Image); index++; handler.postDelayed(runnable, 5000); } } }; handler.postDelayed(runnable,1000); } public void StartTimer() { CountDownTimer timer = new CountDownTimer(15000, 5000) //10 second Timer { public void onTick(long l) { Glide.with(getApplicationContext()).load(imageUrl.get(index)).into(background_Image); index++; } @Override public void onFinish() { SystemClock.sleep(5000); handler.post(new Runnable() { public void run() { finish(); } }); }; }.start(); } )没有类型。它可以有一个类型提示,提示建议输入值的类型与名称关联的信息将具有,但该信息仅是一个提示。这不是规范性的。

内置x根本不使用类型提示。

type()

将始终打印x = 'some string' print(type(x)) ,因为它会检查<class 'str'>指向的实际对象,而不是x本身。

答案 1 :(得分:1)

Python是一种动态类型化的语言,因此变量没有固定的类型。可以使用诸如mypy(http://mypy-lang.org/)之类的工具来检查您正在使用的类型注释,以检查此类类型冲突,但不会出现运行时错误。

从技术上讲,x中存储的实际上是指向数据值的指针。 当您调用type(x)时,解释器将找到x指向的值并返回该值的类型。 Python明确不检查要分配给变量的值的类型。 来自wiki.python.org

  

在动态类型语言中,变量只是绑定到名称的值;该值具有类型-例如“整数”,“字符串”或“列表”-但变量本身没有。

相关问题