[英]How does python keep track of variable data types?
I am mostly familiar with Java and am in the process of learning Python.我最熟悉的是Java,正在学习Python。 I have been playing around with OOP in Python and am slightly confused how it keeps track of data types.
我一直在 Python 中使用 OOP 并且有点困惑它如何跟踪数据类型。 What I am confused about is the get_average_grade() function in the image below.
我感到困惑的是下图中的 get_average_grade() function。 In the for loop how does Python know that student is an object of type Student?
在 for 循环中,Python 如何知道学生是学生类型的 object? Note: the list self.students was assigned to be an empty list in the class' init .
注意:列表 self.students 在班级的init中被分配为一个空列表。
Python variables don't actually have data types. Python 变量实际上没有数据类型。 Python variables are simply symbolic names for a reference (or pointer) to an object.
Python 变量只是对 object 的引用(或指针)的符号名称。 That object has a value (for example 23 or "cat") and a type (for example str or int or Student ).
object 有一个值(例如 23 或“cat”)和一个类型(例如str或int或Student )。 A name can be associated with an int one second and with a Student the next second.
名称可以在一秒钟与一个int关联,然后与一个Student关联。
You can call get_grade()
on any variable.您可以在任何变量上调用
get_grade()
。 If that variable doesn't have a get_grade()
method then the result is an AttributeError exception.如果该变量没有
get_grade()
方法,则结果是 AttributeError 异常。
Some helpful background that all Python programmers should read:所有 Python 程序员都应该阅读的一些有用的背景知识:
Python is smart enough to know what type you want a variable to be when you assign it. Python 足够聪明,可以在分配变量时知道您希望变量是什么类型。 Check this out.
看一下这个。
student = 'Hi Mom!'
print (student)
student = 7
print (student)
student = [1, 2, 3]
print (student)
At any time 'student' can be a string, integer, list, dictionary etc, etc...任何时候'student'都可以是一个字符串,integer,列表,字典等等……
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.