1.
测试:全局变量a在函数内被修改之后,函数外仍然有效;想在内部函数内使用b,需要用nonlocal声明一下
a=100
def outer():
b=10
def inner():
nonlocal b
print("inner b :",b)
b=20
global a
a=1000
inner()
print("outer b :",b)
outer()
print("a:",a)
结果:
2.
测试:
str="global"
def outer():
str="outer"
def inner():
str="inner"
print (str)
inner()
outer()
结果输出:
inner
进程已结束,退出代码
如果分别将几句str注释掉,结果如下:
#str="global"#对应序号3
def outer():
#str="outer"#对应序号2
def inner():
#str="inner"#对应序号1
print (str)
inner()
outer()
结果:
注释①:outer
注释①②:global
注释①②③:<class ‘str’>
3.类中init的用法以及可以给实例增加新的属性
class Student:
def __init__(self,name,score):#self必须位于第一个参数
self.name=name
self.score=score
def say_score(self):#self必须位于第一个参数
print("{0}的得分是:{1}".format(self.name,self.score))
s1=Student("Lily",18)
s1.say_score()
s1.salary=3000#增加新的属性
print(s1.salary)
结果:
Lily的得分是:18
3000
进程已结束,退出代码0
4.通过类对象实现上述过程:
st2=Student
s2=st2("bob",10)
s2.say_score()
5.析构与垃圾回收;第一个销毁的是p2,程序结束后,p1同样被销毁
class Person:
def __del__(self):
print("销毁对象{0}".format(self))
p1=Person()
p2=Person()
del p2
print("程序结束")
结果:
销毁对象<__main__.Person object at 0x0000026D9D6FC390>
程序结束
销毁对象<__main__.Person object at 0x0000026D9D54B240>
进程已结束,退出代码0
6.
class Person:
def __call__(self,salary):
print("算工资啦。。。。")
yearsalary=salary*12
return yearsalary
s=Person()
print(s(5000))
结果:
算工资啦。。。。
60000
进程已结束,退出代码0