参考代码:
# 一:
class Hero:
age = 18
def __init__(self, name, gender, height):
self.name = name
self.gender = gender
self.height = height
def print_init(self):
print("姓名:{} 性别:{} 身高:{} 年纪:{}".format(self.name, self.gender, self.height, self.age))
def print_obj(self):
print("This is a object")
def __add__(self, other):
return 2
hero = Hero("亚索", "男", 168)
hero.print_init()
# 定义两个对象
A = Hero("A", "nan", 170)
B = Hero("B", "nv", 168)
print("两个对象相加返回值:", end='')
print( A + B)
# 定义临时变量:
hero.temp_var = 10
print("打印临时变量temp_var:", end='')
print( hero.temp_var)
#二:
class Father:
def __init__(self, name, age, _gender):
self.name = name
self.age = age
self._gender = _gender
def __print_init(self):
print(f"名字:{self.name} 年龄:{self.age} 性别:{self._gender}")
class Son(Father):
def __print_init(self):
print(f"名字:{self.name} 性别:{self._gender}年龄:{self.age} ")
father = Father("Mike", "male", 28)
print("访问父类_变量:", father._gender)
son = Son("张三", "男", 20)
print("访问子类__方法:", end='')
son._Son__print_init()
print("访问父类的__方法(父类与子类的“性别”和“年龄”已做替换):", end='')
son._Father__print_init()
# 三:
#super的使用:
class A:
def print_info(self):
print("This is A")
def say_something(self):
print("Hello A")
class B:
def print_info(self):
print("This is B")
def say_something(self):
print("Hello B")
class C:
def print_info(self):
print("This is C")
def say_something(self):
print("Hello C")
class D:
def print_info(self):
print("This is D")
def say_something(self):
print("Hello D")
class E(A, B, C, D):
def print_info(self):
# 利用super,让执行print_info时调用B中print_info
super(A, E).print_info(self)
def say_something(self):
# 利用super, 让执行say_something时调用C中say_something
super(B, E).say_something(self)
e = E()
e.print_info()
e.say_something()
# 四:
"""
什么是闭包:
嵌套函数
内层函数引用外层函数的变量(*变量)
在外层函数返回内层函数
"""
def sum_():
result = []
def inner(num):
result.append(num)
print(sum(result))
return inner
sum_data = sum_()
sum_data(10)
sum_data(20)
sum_data(30)
结果:
D:\Python-interpreter\python.exe D:/Python-code/main.py
姓名:亚索 性别:男 身高:168 年纪:18
两个对象相加返回值:2
打印临时变量temp_var:10
访问父类_变量: 28
访问子类__方法:名字:张三 性别:20年龄:男
访问父类的__方法(父类与子类的“性别”和“年龄”已做替换):名字:张三 年龄:男 性别:20
This is B
Hello C
10
30
60
Process finished with exit code 0