metaclass
What are metaclasses in Python?
举个例子:
type
可以用于创建类,和直接创建类的操作是一样的
>>> class Foo():
bar=True
>>> Foo.bar
True
>>> f=Foo()
>>> f
<Foo object at 0x7f2142616b38>
>>> Goo=type('Goo',(),{'bar':True})
>>> Goo
<class 'Goo'>
>>> Goo.bar
True
>>> g=Goo()
>>> g
<Goo object at 0x7f21426627f0>
判断变量是否为整数
Checking whether a variable is an integer or not
定义一个类,设置object
为int
,那么就只能输入int
类型的数
>>> class Spam(int):
pass
当输入是 2
或者 ’2‘
时,都不会报错
>>> x = Spam(2)
>>> y = Spam('2')
但是如果输入的是 ‘2_’, 很明显是字符串时,就会报错
>>> z = Spam('2_')
Traceback (most recent call last):
File "<input>", line 2, in <module>
ValueError: invalid literal for int() with base 10: '2_'
下面讲,如何判断变量是否为整数
第一反应是type(x)
,但其实是不对的,应该用isinstance(<var>, int)
比如在刚才的类中,定义了x = Spam(2)
和 y = Spam('2')
>>> type(x)==int
False
>>> type(y)==int
False
>>> isinstance(x,int)
True
>>> isinstance(y,int)
True
type
还有一个神奇的地方,在pycharm中使用的时候,
在注释中,它后面加个冒号,结果后面的变量会高亮,而普通的则不会
学习资源
python在线学习和coding,无需安装环境,在最上方还有其他语言如Java、C++可以学习
https://www.learnpython.org/
stackoverflow.com也很有意思,下面这个链接是按votes
数排序的,基本都是有用的答案
https://stackoverflow.com/questions/tagged/python?sort=votes&pageSize=15