从MonkeyLei:Python-快速练习(入门杂练了一把Python2.0+/Python3.0+)-菜鸟教程一路过来。。目前已经做了很多练习实践了:
![](https://img.haomeiwen.com/i12874069/00030e6be4da6edf.jpg)
继续看点高级点的用法吧~~~ 如果真要封装更好的话,还是有涉及下类的学习这些的呀。。。毕竟很多模块基本都是采用类做了封装的。。
直接练习 higher_practice.py
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
# 文件名:higher_practice.py
# 继承object的类Student
class Student(object):
# 限制了我们只能绑定、使用这些变量
__slots__ = ('name', 'age', 'mother', '__private_addr', '__like_private_by_set_get')
def funtion(self):
print('我是一个普通函数')
def __function2(self, inner):
pass
# 定义一个构造方法
def __init__(self, name, age):
self.name = name
self.age = age
# 输出对象信息自定义
def __str__(self):
return str('姓名: ' + self.name + ' 年龄: ' + str(self.age))
# 如果获取没有的属性,可以给出如下结果
def __getattr__(self, item):
return '你的属性木有啊!'
# 对象可以作为方法调用,此时需要实现call方法
def __call__(self, *args, **kwargs):
print('我是一个学生对象,你可以继承我实现一个大学生!')
# 将类方法转换为类属性,可以用.直接获取属性值或者对属性进行赋值
# 被装饰后的like_private_by_set_get,已经不是这个实例方法like_private_by_set_get了,而是property的实例like_private_by_set_get
@property
def like_private_by_set_get(self):
return self.__like_private_by_set_get
@like_private_by_set_get.setter
def like_private_by_set_get(self, value):
self.__like_private_by_set_get = value
if __name__ == '__main__':
sd = Student('test', 112)
# __标识的私有方法不能直接被调用
sd.funtion()
# sd.__funtion2(110)
# 有__slots__,这里就会报错
# sd.nothter = '动态绑定一个属性'
sd.mother = '母亲伟大!'
print(sd)
print(sd.mother)
print(sd.parent)
# 对象作为方法被call
sd()
# __私有变量不能直接操作
try:
sd.__private_addr = '我家在西昌'
print(sd.__private_addr)
except Exception as err:
print(err)
# @property注解方法实现私有变量赋值
sd.like_private_by_set_get = '通过@property实现私有变量的间接访问; 当然get/set也可以'
print(sd.like_private_by_set_get)
# type动态创建一个类,牛皮呀,大兄弟
# 类名称 继承类 方法名称:方法的引用
dynamic_class = type('MyClass', (object,), {'hello': sd.funtion})
print(type(dynamic_class)) # 当前还是一个type类
dynamic_class.hello()
dynamic_class_instance = dynamic_class()
print(type(dynamic_class_instance)) # 当前实例化一个新的类后,就是真的叫MyClass的类了
# 这里有个案例,实现简单的ORM框架 https://www.liaoxuefeng.com/wiki/1016959663602400/1017592449371072
# 主要是根据表的结构动态定义出对应的类,头是有点大,卧槽~~~~后面好好学习java arm, ioc这些...加深反射注解
结果:
D:\PycharmProjects\python_study\venv3.x\Scripts\python.exe D:/MEME/fz/doc/Python/python_study/protest/higer_practice.py
我是一个普通函数
姓名: test 年龄: 112
母亲伟大!
你的属性木有啊!
我是一个学生对象,你可以继承我实现一个大学生!
'Student' object has no attribute '__private_addr'
通过@property实现私有变量的间接访问; 当然get/set也可以
<class 'type'>
我是一个普通函数
<class '__main__.MyClass'>
Process finished with exit code 0
我是参考 面向对象高级编程 练习了一段时间,你可以针对性的调一些高级点的来实践哈!还是有好处的,还能了解到orm这些知识。。java也是。。spring,mybatis这些可能都会略看到。。。 今天任务差不了。公司的一个bug确认。。然后早点下班回去看视频,完成另外一个任务。。。还有需要锻炼一下.......
网友评论