5.python高级一/demo03_python环境变量路径.py
from loguru import logger
import sys
sys.path.append('/Users/toby/Downloads/PythonAdvanced/code/pythonAdvanced5Verify')
for path in sys.path:
logger.debug(path)
5.python高级一/demo09_xxxsetter和xxxdeleter装饰器.py
# -*- coding:utf-8 -*-
# coding=utf-8
import os
from loguru import logger
logger.add(os.path.join(os.path.dirname(__file__) , os.path.basename(__file__).split('.')[0]+'.z.log'))
class Goods(object):
"""python3中默认继承object类
以python2、3执行此程序的结果不同,因为只有在python3中才有@xxx.setter @xxx.deleter
"""
@property
def price(self):
logger.debug('@property')
@price.setter
def price(self, value):
logger.debug('@price.setter')
@price.deleter
def price(self):
logger.debug('@price.deleter')
obj = Goods()
obj.price # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
obj.price = 123 # 自动执行 @price.setter 修饰的 price 方法,并将 123 赋值给方法的参数
del obj.price # 自动执行 @price.deleter 修饰的 price 方法
# 2023-06-29 23:33:23.225 | DEBUG | __main__:price:16 - @property
# 2023-06-29 23:33:23.225 | DEBUG | __main__:price:20 - @price.setter
# 2023-06-29 23:33:23.225 | DEBUG | __main__:price:24 - @price.deleter
5.python高级一/demo18_call方法.py
# __call__方法
class CallTest(object):
def __init__(self):
print('execute init method')
pass
def __call__(self, *args, **kwargs):
print('__call__')
obj = CallTest() # 执行 __init__
# 把一个对象当做一个函数执行,就回调用call 方法
obj() # 执行 __call__
5.python高级一/demo12.py
# -*- coding:utf-8 -*-
# -*- coding:utf-8 -*-
class Goods(object):
def __init__(self):
# 原价
self.original_price = 100
# 折扣
self.discount = 0.8
def get_price(self):
# 实际价格 = 原价 * 折扣
new_price = self.original_price * self.discount
return new_price
def set_price(self, value):
self.original_price = value
def del_price(self):
del self.original_price
PRICE = property(get_price, set_price, del_price, '价格属性描述。。。。')
obj = Goods()
original_price = obj.PRICE # 获取商品价格
print(original_price)
obj.PRICE = 200 # 修改商品原价
desc = Goods.PRICE.__doc__
print(desc)
del obj.PRICE # 删除商品原价
5.python高级一/demo21_getitem_setitem_delitem.py
# __getitem__、__setitem__、__delitem__
class Foo(object):
def __getitem__(self, key):
print('__getitem__', key)
def __setitem__(self, key, value):
print('__setitem__', key, value)
def __delitem__(self, key):
print('__delitem__', key)
obj = Foo()
result = obj['k1'] # 自动触发执行 __getitem__
obj['k2'] = 'laowang' # 自动触发执行 __setitem__
del obj['k1'] # 自动触发执行 __delitem__
5.python高级一/demo06.py
import os
from loguru import logger
logger.add(os.path.join(os.path.dirname(__file__) , os.path.basename(__file__).split('.')[0]+'.z.log'))
class Money(object):
def __init__(self):
self.__money = 100
def getMoney(self):
return "¥ %d" % self.__money
def setMoney(self, value):
if isinstance(value, int):
self.__money = value
else:
print("error:不是整型数字")
m = Money()
m.setMoney(100)
res = m.getMoney()
logger.debug(res)
5.python高级一/demo19_dict方法.py
import os
from loguru import logger
logger.add(os.path.join(os.path.dirname(__file__) , os.path.basename(__file__).split('.')[0]+'.z.log'))
# __dict__方法
class Province(object):
country = 'China'
def __init__(self, name, count):
self.name = name
self.count = count
def func(self, *args, **kwargs):
print('func')
# 获取类的属性,即:类属性、方法、
logger.debug(Province.__dict__) # => {'__module__': '__main__', 'country': 'China', '__init__': <function Province.__init__ at 0x100fdf1a0>, 'func': <function Province.func at 0x100fdf240>, '__dict__': <attribute '__dict__' of 'Province' objects>, '__weakref__': <attribute '__weakref__' of 'Province' objects>, '__doc__': None}
obj1 = Province('山东', 10000)
logger.debug(obj1.__dict__) # 输出:{'count': 10000, 'name': '山东'}
obj2 = Province('山西', 20000)
logger.debug(obj2.__dict__)# 输出:{'count': 20000, 'name': '山西'}
5.python高级一/demo05_类方法传入实例调用实例方法.py
import os
from loguru import logger
logger.add(os.path.join(os.path.dirname(__file__) , os.path.basename(__file__).split('.')[0]+'.z.log'))
class MiniOS(object):
"""MiniOS 操作系统类 """
def __init__(self, name):
self.name = name
self.apps = [] # 安装的应用程序名称列表
def __str__(self):
"""打印实例会调用的方法
Returns:
_type_: _description_
"""
return "%s 安装的软件列表为 %s" % (self.name, str(self.apps))
def install_app(self, app):
# 判断是否已经安装了软件
if app.name in self.apps:
print("已经安装了 %s,无需再次安装" % app.name)
else:
app.install()
self.apps.append(app.name)
class App(object):
def __init__(self, name, version, desc):
self.name = name
self.version = version
self.desc = desc
def __str__(self):
return "%s 的当前版本是 %s - %s" % (self.name, self.version, self.desc)
def install(self):
logger.debug("将 %s [%s] 的执行程序复制到程序目录..." % (self.name, self.version))
class PyCharm(App):
pass
class Chrome(App):
def install(self):
logger.warning("正在解压缩安装程序...")
super().install()
linux = MiniOS("Linux")
logger.debug(linux)
pycharm = PyCharm("PyCharm", "1.0", "python 开发的 IDE 环境")
chrome = Chrome("Chrome", "2.0", "谷歌浏览器")
# 方法中传入一个类,然后在类中其相关的方法
linux.install_app(pycharm)
linux.install_app(chrome)
linux.install_app(chrome)
logger.debug(linux)
5.python高级一/demo07_装饰方法成属性.py
class Money(object):
def __init__(self):
self.__money = 100
@property
def getMoney(self):
return "¥ %d" % self.__money
def setMoney(self, value):
if isinstance(value, int):
self.__money = value
else:
print("error:不是整型数字")
m = Money()
m.setMoney(100)
res = m.getMoney
print(res)
5.python高级一/demo17_del方法.py
# __del__方法
class DelTest(object):
def __init__(self):
print("__init__方法运行了")
def __del__(self):
print("__del__方法运行了")
defTest = DelTest()
5.python高级一/demo16_init方法.py
# __init__方法
class InitTest(object):
def __init__(self, name):
print("__init__执行了")
self.name = name
self.age = 18
laowang = InitTest('laowang')
5.python高级一/demo18_call和init的区别.py
# __call__方法
class CallTest(object):
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('__call__')
obj = CallTest() # 执行 __init__
obj() # 执行 __call__
5.python高级一/demo08.py
# -*- coding:utf-8 -*-
# ############### 定义 ###############
class Pager:
"""
旧式类
"""
def __init__(self, current_page):
# 用户当前请求的页码(第一页、第二页...)
self.current_page = current_page
# 每页默认显示10条数据
self.per_items = 10
@property
def start(self):
val = (self.current_page - 1) * self.per_items
return val
@property
def end(self):
val = self.current_page * self.per_items
return val
# ############### 调用 ###############
p = Pager(1)
print(p.start) # 就是起始值,即:m
print(p.end) # 就是结束值,即:n
5.python高级一/demo02_私有属性和私有方法.py
class Person(object):
def __init__(self, name, age, taste):
self.name = name
self._age = age
self.__taste = taste
def showperson(self):
print(self.name)
print(self._age)
print(self.__taste)
def dowork(self):
self._work()
self.__away()
def _work(self):
"""私有方法
"""
print('my _work')
def __away(self):
"""私有方法
"""
print('my __away')
p = Person(name="lisi", age=18, taste="哈哈")
print(p.name)
print(p._age)
# 下面的方法不能访问
# print(p.__taste)
# 按照下面的方法可以访问
# 如何访问私有属性
print(p._Person__taste)
5.python高级一/demo14_doc信息.py
class Doc(object):
"""这里是当前这个类的描述信息
Args:
object (_type_): _description_
"""
pass
d = Doc()
print(d.__doc__)
5.python高级一/demo04_静态方法_类方法.py
class Person(object):
def foo(self):
"""
实例方法
:return:
"""
print(id(self)) # 用来查看对象的id
@staticmethod
def static_foo():
"""
静态方法
:return:
"""
print("in static")
@classmethod
def class_foo(cls):
"""
类方法
:return:
"""
print("in class")
p1 = Person()
p2 = Person()
p1.foo()
p2.foo()
p1.static_foo()
p1.class_foo()
# 运行顺序 实例->类对象->类对象方法
# 可以使用__class__来调用类对象方法
p1.__class__.class_foo()
5.python高级一/demo11.py
# -*- coding:utf-8 -*-
# coding=utf-8
class Foo(object):
def get_bar(self):
print("getter...")
return 'laowang'
def set_bar(self, value):
"""必须两个参数"""
print("setter...")
return 'set value' + value
def del_bar(self):
print("deleter...")
return 'laowang'
BAR = property(get_bar, set_bar, del_bar, "description...")
obj = Foo()
bar = obj.BAR # 自动调用第一个参数中定义的方法:get_bar
print(bar)
obj.BAR = "alex" # 自动调用第二个参数中定义的方法:set_bar方法,并将“alex”当作参数传入
desc = Foo.BAR.__doc__ # 自动获取第四个参数中设置的值:description...
print(desc)
del obj.BAR # 自动调用第三个参数中定义的方法:del_bar方法
5.python高级一/demo15_test.py
# -*- coding:utf-8 -*-
class Person(object):
def __init__(self):
self.name = 'laowang'
5.python高级一/demo15_module和class.py
# __module__和__class__
from demo15_test import Person
obj = Person()
print(obj.__module__) # 输出 test 即:输出模块
print(obj.__class__) # 输出 test.Person 即:输出类
5.python高级一/demo10.py
# -*- coding:utf-8 -*-
class Goods(object):
def __init__(self):
# 原价
self.original_price = 100
# 折扣
self.discount = 0.8
@property
def price(self):
# 实际价格 = 原价 * 折扣
new_price = self.original_price * self.discount
return new_price
@price.setter
def price(self, value):
self.original_price = value
@price.deleter
def price(self):
del self.original_price
obj = Goods()
original_price = obj.price # 获取商品价格
print(original_price)
obj.price = 200 # 修改商品原价
del obj.price # 删除商品原价
5.python高级一/demo20_str方法.py
# __str__方法
class StrTest(object):
def __str__(self):
return 'laowang'
obj = StrTest()
print(obj)