自我总结21

classmethod

翻译:一个类方法

classmethod是一个装饰器,可以装饰给类内部的方法,使该方法绑定给类来使用

​ --对象的绑定方法的特殊之处

​ 由对象来调用,会将对象当作第一个参数传给该方法

​ --类的绑定方法特殊之处

​ 由类来调用,会将类当作第一个参数传给该方法

class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def tell_info(cls):  # cls==People
        print(cls)
        print('此处是类方法...')
        pass


p = People('tank', 18)

# 绑定方法
p.tell_info() # <class '__main__.People'>此处是类方法...

# 绑定类
People.tell_info() # <class '__main__.People'>此处是类方法...
import hashlib
import uuid
import settings
class Teacher:
    def __init__(self, user, pwd):
        self.user = user
        self.pwd = pwd

    # 主页
    def index(self):
        if self.user == 'tank' and self.pwd == '123':
            print('验证通过,显示主页...')

    @classmethod
    def login_auth_from_settings(cls): # cls = Teacher
        obj = cls(settings.USER, settings.PWD)
        return obj  #   return = obj ---> Teacher() ---> cls()

'''
转换的思路
# Teacher.login_auth_from_settings()--->
Teacher(settings.USER, settings.PWD)--->
Teacher(settings.USER, settings.PWD).index()

 settings.USER = 'tank
 settings.PWD = '123'
'''    



obj = Teacher.login_auth_from_settings()
obj.index()


tea1 = Teacher('tank', '123')
print(tea1)

staticmethod

staticmethod是一个装饰器,可以装饰给类内部的方法,使该方法即不绑定给对象,也不绑定给类

uuid模块

是一个加密模块,uuid4通过时间戳生成一个世界上唯一的字符串

import hashlib
import uuid
import settings
class Teacher:
    def __init__(self, user, pwd):
        self.user = user
        self.pwd = pwd

    # 主页
    def index(self):
        if self.user == 'tank' and self.pwd == '123':
            print('验证通过,显示主页...')

    @classmethod
    def login_auth_from_settings(cls): # cls = Teacher
        obj = cls(settings.USER, settings.PWD)
        return obj  #   return = obj ---> Teacher() ---> cls()


    @staticmethod
    def create_id():
        # 生成一个唯一的id字符串
        uuid_obj = uuid.uuid4()
        md5 = hashlib.md5()
        md5.update(str(uuid_obj).encode('utf-8'))
'''
uuid_obj ---> str(uuid_obj) 转化成字符串类型
uuid_obj本身是对象,不能update   

'''        
        return md5.hexdigest()




if __name__ == '__main__':
    print(type(uuid.uuid4())) #<class 'uuid.UUID'>
    
    
    
# @staticmethod装饰器,create_id()都不需要传参数
print(Teacher.create_id())
tea1 = Teacher('tank', '123')
print(tea1.create_id())

isinstance(参数1,参数2)

​ python内置的函数,可以传入两个参数,用于判断参数1是否为参数2 的一个实例

***判断一个对下个是否是一个类的实例

issubclass(参数1, 参数2)

python内置的函数,可以传入两个桉树,用与判断参数1是否是参数2的子类。
`

*** 判断一个类是否是另一个类的子类

# __class__: 对象的属性,获取该对象当前的类。

class Foo:
    pass

class Goo(Foo):
    pass


foo_obj = Foo()

# print(Foo.__dict__) == print(foo_obj.__class__.__dict__)


print(isinstance(foo_obj, Foo)) # True
# foo_obj是Foo的实例
print(isinstance(foo_obj, Goo))  # False
# foo_obj不是Goo的实例

print(issubclass(Goo, Foo))  # True 
# Goo是Foo的子类 

反射

指的是通过“字符串”对 对象或类的属性进行操作

'''
    - hasattr: 通过字符串,判断该字符串是否是对象或类的属性。
    - getattr: 通过字符串,获取对象或类的属性。
    - setattr: 通过字符串,设置对象或类的属性。
    - delattr: 通过字符串,删除对象或类的属性。
'''

class People:
    country = 'China'

    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex


# 普通方式
p = People('tank', 17, 'male')
print('name' in p.__dict__)  # True
print('country' in People.__dict__)  # True
print('country2' in People.__dict__)  # False
# hasattr
print(hasattr(p, 'name'))  # True
print(hasattr(People, 'country'))  # True


# 普通方式
p = People('tank', 17, 'male')
print(p.__dict__.get('name'))  # tank
print(p.__dict__.get('level', '9'))  # 9

# getattr
print(getattr(p, 'name', 'jason_sb'))  # tank
print(getattr(p, 'name1', 'jason_sb'))  # jason_sb
print(getattr(People, 'country2', 'China'))


# setattr
# 普通
p.level = 10
print(p.level)  # 10

# 反射
setattr(p, 'sal', '3.0')
print(hasattr(p, 'sal'))  # True


# delattr
# 普通
del p.level
print(hasattr(p, 'level'))  # False

# 反射
delattr(p, 'sal')
print(hasattr(p, 'sal'))  # False
'''
反射小练习:
'''
class Movie:
    def input_cmd(self):
        print('输入命令:')
        while True:
            cmd = input('请输入执行的方法名:').strip()

            # 若用户输入的cmd命令是当前对象的属性
            if hasattr(self, cmd):
                method = getattr(self, cmd)
                method()
            else:
                print('命令错误,请重新输入!')

    def upload(self):
        print('电影开始上传...')

    def download(self):
        print('电影开始下载...')


movie_obj = Movie()
movie_obj.input_cmd()

魔法方法

'''
凡是类内部定义,以“__开头__结尾”的方法都称之为魔法方法,又称“类的内置方法”
魔法方法会在某些条件成立时触发

__init__:在调用类时触发
__str__:会在打印对象时触发
__del__:会在程序执行结束是触发,对象销毁
__getattr__:会在对象.属性时,“属性没有”的情况下才会触发
__setattr__:会在“对象.属性 = 属性值”时触发
__call__:会在对象被调用时触发
__new__:会在__init__执行前触发
'''

class Foo:
    def __init__(self):
        print('再调用类触发...')
    def __str__(self):
        print('')
        # 必须要有一个返回值,返回值必须是字符串类型
        return '字符串'
    
# 文件保存
class MyFile(object):
    def __init__(self, file_name, mode='r', encoding='utf-8'):
        self.file_name = file_name
        self.mode = mode
        self.encoding = encoding

    def file_open(self):
        self.f = open(self.file_name, self.mode, encoding=self.encoding)

    def file_read(self):
        res = self.f.read()
        print(f'''
        当前文件名称: {self.file_name}
        当前文件数据: {res}
        ''')

    # def close(self):
    #     self.f.close()
    def __del__(self):
        self.f.close()
        print('文件关闭成功!')

f = MyFile('jason雨后的小故事.txt')
f.file_open()
f.file_read()

print('程序结束,对象被销毁!')

单例模式

单例模式指的是单个实例,实例指的是调用类产生的对象

实例化多个对象会产生不同的内存地址,单例可以让所有调用者,在调用类产生对象的情况下都指向同一份内存地址。 例如: 打开文件。

单例的目的: 为了减少内存的占用。

class File:

    __instance = None

# 单例方式1:
 @classmethod
 def singleton(cls, file_name):
     if not cls.__instance:
          obj = cls(file_name)
          cls.__instance = obj
      return cls.__instance
class File:

    __instance = None

# 单例方式2:
    def __new__(cls, *args, **kwargs):
        # cls.__new__(cls, *args, **kwargs)
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance

    def __init__(self, file_name, mode='r', encoding='utf-8'):
        self.file_name = file_name
        self.mode = mode
        self.encoding = encoding

    def open(self):
        self.f = open(self.file_name, self.mode, encoding=self.encoding)

    def read(self):
        res = self.f.read()
        print(res)

    def close(self):
        self.f.close()


# 方式1:
# obj1 = File.singleton('jason雨后的小故事.txt')  # singleton(cls)
# obj2 = File.singleton('jason雨后的小故事.txt')  # singleton(cls)
# obj3 = File.singleton('jason雨后的小故事.txt')  # singleton(cls)
# obj1 = File('jason雨后的小故事.txt')
# obj2 = File('jason雨后的小故事.txt')
# obj3 = File('jason雨后的小故事.txt')
# print(obj1)
# print(obj2)
# print(obj3)

# 方式2:
obj1 = File('jason雨后的小故事.txt')  # singleton(cls)
obj2 = File('jason雨后的小故事.txt')  # singleton(cls)
obj3 = File('jason雨后的小故事.txt')  # singleton(cls)
print(obj1)
print(obj2)
print(obj3)
posted @ 2019-10-13 10:34  jzm1201  阅读(55)  评论(0编辑  收藏  举报