002day_反射,两个装饰器方法,__call__,__len__,__str__,__repr__

**super**
 super遵循的是mro算法
    只在新式类中能使用
    py2新式类中需要自己添加参数(子类名,子类对象)
**封装**
    1.广义上的封装
    2.狭义上的封装: __名字
		方法名私有化
        实例变量私有化
        静态变量私有化
        私有化的特点:
            只能在类的内部使用
            私有的各种静态变量和方法不能继承
            不能被子类继承

**内置函数**
    判断一个变量是否可调用
        callable(名字)
    装饰器
        @prooerty把一个方法伪装成属性
        给伪装成属性的方法赋值 @函数名.setter装饰器
**反射相关**
    hasattr()
    getattr()
    字符串数据类型的变量,采用getattr(对象,‘变量名’)获取变量的值
class File:
    lst = [('读文件','read'), ('写文件','write'),
           ('删除文件','remove'), ('文件重命名','rename')
        ,('复制','copy')]
    def __init__(self,filepath):
        self.filepath = filepath
    def write(self):
        print('in write')
    def read(self):
        print('in read')
    def remove(self):
        print('in remove')
    def rename(self):
        print('in rename')
    def copy(self):
        print('in copy')
f = File('ss')
lst = ['读文件','写文件','删除文件','文件重命名','复制']
for index,opt in enumerate(File.lst,1):
    print(index,opt[0])
num = int(input('请输入你要选择的序号>>>'))
# print(File.lst[num-1][1])
if hasattr(f,File.lst[num-1][1]):
    getattr(f,File.lst[num-1][1])()
#两个装饰器
    #@classmethod
    #@staticmethod
    '''
classmethod
1.定义一个方法,默认传self,但这个self没被使用
2.在这个方法利用到了当前的类名,或者准备使用这个类的内存空间的名字的时候
把一个对象绑定的方法修改成一个类方法:在方法中仍然可以引用类中的静态变量,可以不用实例化对象,直接用类名在外部调用这个方法
'''
class Goods:
    __discount = 0.8
    def __init__(self):
        self.__price = 5
        self.price = self.__price*self.__discount
        # print(id(self.__discount))
        # print(id(Goods.__discount))
    @classmethod    
    def change_discount(cls,new_discount):
        cls.__discount = new_discount
        print(cls.__discount)
Goods.change_discount(0.6)
apple = Goods()
print(apple.price)

# apple = Goods()
# # print(apple.price)
# apple.change_discount(0.6)
# apple2 = Goods()
# print(apple2.price)
# print(apple.price)
# print(apple.__dict__)
# print(apple2.__dict__)

import time
class Data:
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day
    @classmethod
    def today(cls):
        struct_t = time.localtime()
        data = cls(struct_t.tm_year,struct_t.tm_mon,struct_t.tm_mday)
        return data
tody = Data.today()
print(tody.year)
print(tody.day)
print(tody.month)
```python
'''
staticmethod

'''
# def login():
#     print('登录')
class User:
    @staticmethod
    def login(a,b):#本身是一个普通的函数,被挪到类的内部执行,那么直接给这个函数添加staticmethod装饰器就行
        print('登录',a,b)
        #在函数的内部既不会用到self变量,也不会用到cls类

User.login(1,2)
obj = User()
obj.login(3,4)
# 能定义到类中的内容
# 静态变量 是个所有对象共享的变量 由对象/类调用,但不能重新赋值
# 绑定方法 自带self参数的函数,由对象调用
# 类方法 是个自带cls参数的函数 由对象/类调用
# 静态方法 只是个普通函数 由对象和类调用
# property属性 是个伪装成属性的方法,由对象调用 但不加括号
class A:
    country = 'China'
    def func(self):
        print(self.__dict__)
    @classmethod
    def clas_func(cls):
        print(cls)
    @staticmethod
    def stat_func():
        print('普通函数')
    @property
    def name(self):
        return 'wahaha'

a = A()
a.country='123'
print(a.country)
print(A.country)
结果
123
China
# callable(对象)
#对象()能不能运行就是callable判断的事
class A:
    pass
obj = A()
print(callable(obj))
结果:
FALSE

class B:
    def __call__(self, *args, **kwargs):
        print('helo!oleh')
obj1 = B()
print(callable(obj1))
obj1()
结果:
True
helo!oleh
class Cls:
    def __init__(self,name):
        self.name = name
        self.student = []

    def __len__(self):
        return len(self.student)
qq = Cls('helo')
qq.student.append('HELO!')
qq.student.append('HELO!1')
qq.student.append('HELO!2')
qq.student.append('HELO!3')
print(len(qq.student))
print(qq.__len__())
print(len(qq))#调用__len__方法 ===>> qq.__len__()
结果:
4
4
4
#__new__
class A:
    def __new__(cls, *args, **kwargs):
        o = super().__new__(cls)
        print('执行new',o)
        return o
    def __init__(self):
        print('执行init',self)
A()

# 实例化的时候
# 先创建一个对象空间,有一个指针指向类 --> __new__
# 调用init

# 设计模式 --单例模式
# 一个类从头到尾只会创建一次self的空间

class B:
    __instance = None
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self,cloth,pants):
        self.cloth = cloth
        self.pants = pants

b1 = B('红毛衣','绿皮裤')
b2 = B('红毛衣','黑豹文')
print(b1)
print(b1.pants)
print(b2)
print(b2.pants)
结果:
<__main__.B object at 0x7f4a550ae9a0>
黑豹文
<__main__.B object at 0x7f4a550ae9a0>
黑豹文
python的模块单例模式
单例.py
class Baby:
    def __init__(self,cloth,pants):
        self.cloth = cloth
        self.pants = pants
baby = Baby('红上衣','鹿皮裤')

调用单例模式.py
from 单例 import baby
print(baby)
print(baby)
print(baby)
结果:
<单例.Baby object at 0x7fdd3416e8b0>
<单例.Baby object at 0x7fdd3416e8b0>
<单例.Baby object at 0x7fdd3416e8b0>
#__str__方法:print(对象)不返回内存地址,返回想要打印的内容(只能是str类型)
#在打印一个对象的时候调用的是__str__方法,
#在%s拼接一个对象的时候调用__str__方法
#在str(对像)的时候
# 当我们打印一个对象,用%s进行字符串拼接 或者str(对象)总是调用__str__方法
# 如果找不到__str__方法,就调用__repr__方法
# __repr__不仅是__str__的替代品,还有自己的功能
# 用%r进行字符串拼接的时候 或者repr(对象)的时候总是调用这个对象的__repr__方法
#打印/展示对象的时候更直观的显示对象内容,%s,str(),print()
#__repr__:repr是str的备胎,同时还和%r和repr()有合作关系
class Course:
    def __init__(self,name,price,period):
        self.name = name
        self.price = price
        self.period = period

    def __str__(self):
        return 'aaaaaaaa'
python = Course('python',21800,'6 months')
linux = Course('linux',19800,'5 months')
mysql = Course('mysql',12800,'3 months')
go = Course('go',15800,'4 months')
print(go)
结果:
aaaaaaaa

class Course:
    def __init__(self,name,price,period):
        self.name = name
        self.price = price
        self.period = period
    def __str__(self):
        return ','.join([self.name,str(self.price),self.period])
        # return 'aaaaaaaa'
python = Course('python',21800,'6 months')
linux = Course('linux',19800,'5 months')
mysql = Course('mysql',12800,'3 months')
go = Course('go',15800,'4 months')
print(go)#在打印一个对象的时候调用的是__str__方法,
print(str(go))#在str(对像)的时候
print('这是%s' %(go))#在%s拼接一个对象的时候调用__str__方法
结果:
go,15800,4 months
go,15800,4 months
这是go,15800,4 months
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值