面向对象高阶

面向对象高阶

classmethod

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

类的绑定方法特殊 之处

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

staticmethod

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

classmethid和staticmethod实列

import hashlib
import uuid	# 是一个加密模块。uuid4通时间戳生成世界上唯一的字符
import settings

class Teacher:
    def __init__(self,user,pwd)
    self.user=user
	self.pwd
    
    def index(self)
    if self.user=='jj' and self.pwd=='123'
    	print('验证通过显示主页')
        
    @classmethed # 绑定给类使用
    def login_auth_from_setting(cls)
    	ojb=cls(settings.USER,settings.PWD)
        return ojb  # 就是Teacher()
    
    @staticmetod # 当作普通的函数
    def create_id():
    # 生成一个唯一的id字符串
    uuid_ojb=uuid.uuid4() 
    md5=hashlib.md5()
    md5.update(str(uuid_ojb).encode('utf-8'))
    return md5.hexdigest()
 
    
    
ojb=Teacher.login_auth_from_setting()
ojb.index()

isinstance

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

判断对象和类是否有关系

isssubclass

python内置的函数,可以传入两个参数,用于判断参数1是否是参数2的子类

判断类与类是否有关系

class Foo:
	pass

class Boo(Foo):
    pass

foo_obj= Foo()
prinit(isinstance(foo_ojb,Foo)) # Ture
print(isinstance(foo_ojb,Boo)) # False
print(issubclass(Boo,Foo)) # True

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

反射

反射:指的是通过"字符串"对,对象或类的属性进行操作

  • 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('JJ','17','male')
print(hasattr(p,'name'))	# True
print(getattr(p,'name','bb'))	# JJ,有则返回对象或类的值
print(getattr(p,'name1','bb'))	# bb,,没有则返回默认值

print(setattr(p,'sal','30'))	# 没有则创建一个sal=30,有则修改
print(p.sal)	# 30

print(delattr(p,'sal'))	# None 

反射实列

class Movie:
    def input_cmd(self):
        print('请输入指令')
        while True:
            cmd = input('请输入执行方法名').strip()
            if hasattr(self, cmd):
                method = getattr(self, cmd)
                return method()
            else:
                print('命令错误')

    def upload(self):
        print('电影还是上传')

    def download(self):
        print('电影开始下载')
movie=Movie()
movie.input_cmd()

魔法方法

凡是在类内部定义,”以__开头__结尾“ 的方法都称之为魔法方法,又称类的内置方法。

魔法方法会在某个条件成立时触发

__init__: 在调用类时触发
__srt__:会在打印对象时触发
__del__:会在对象被销毁钱执行该方法。该方法会在最后执行
__getattr__:会在“对象.属性”时,属性没有”的情况下会触发
__setattr__:会在“对象.属性 = 属性值”时触发
__call__:会在对象被调用时触发
__new__:会在__init__执行前触发


class MyFlie(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 __del__(self):
        self.f.close()
        print('文件关闭成功!')
f=MyFile('花花.text')
f.file_open()
f.file_read()

单列模式

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

实列化多个对象会产生不同的内存地址,单列可以让所有调用者,在调用类产生

对象的情况下都指像同一份内存地址。列如打开文件

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

class File:
    __instnace = None
    
  '''
  	# 方法一
   @classmethod
    def singleton(cls,file_name)
    if not cls.__instance:
        obj=cls(file_name)
        __instance = obj
    return cls.__instnace 

  	# 方法二
  	def __new__(cls,*args,**kwargs)
  		if not cls.__instance:
  			cls.__instance=boject.__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()
    
    
posted @ 2019-10-12 20:16  鸿鸿1  阅读(104)  评论(0编辑  收藏  举报