【Python】魔法方法

概述

在这里插入图片描述

repr

定制对象显示规则

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


stu = Student('wyb', 23)
print(stu)
print(stu.__repr__())

输出:
<main.Student object at 0x0000026C9D9EB5C8>
<main.Student object at 0x0000026C9D9EB5C8>

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

    def __repr__(self):
        return 'Student[name=' + self.name + ',age=' + str(self.age) + ']'

stu = Student('wyb', 23)
print(stu)
print(stu.__repr__())

输出:
Student[name=wyb,age=23]
Student[name=wyb,age=23]

del

定制对象的析构方法,常用在手动释放外部资源的情况。

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.f = open('adult-all.csv')

    def __del__(self):
        print('析构')
        self.f.close()

stu = Student('wyb', 23)
a = stu  # 引用次数不为零, del stu先不执行
del stu
print('***********')

'''
输出:
***********
析构
'''

new

创建类的实例
init:负责初始化类的实例

class Student:
    def __new__(cls, *args, **kwargs):  # 创建类的实例
        print('new()方法')

    def __init__(self):  # 初始化类的实例,实例由new方法传递过来,即self。没有传递,所以init没被调用
        print('init()方法')

stu = Student()

'''
输出:
new()方法
'''
class Student:
    def __new__(cls, *args, **kwargs):  # 创建类的实例
        print('new()方法')
        return object.__new__(cls)  # 调用init

    def __init__(self):  # 初始化类的实例,实例由new方法传递过来,即self。
        print('init()方法')

stu = Student()

'''
输出:
new()方法
init()方法
'''
class newint(int):
    def __new__(cls, value):
        print('new...')
        return int.__new__(cls, abs(value))

a = newint(-4.3)
print(a)

输出:
new…
4

实现类的单例模式

class Student:
    def __init__(self, name):  # 初始化类的实例,实例由new方法传递过来,即self。
        print('init()方法,{}'.format(name))


stu1 = Student('zhangsan')
stu2 = Student('zhang')
print(stu1)
print(stu2)
'''
输出:
init()方法,zhangsan
init()方法,zhang
<__main__.Student object at 0x000001DE1223B388>
<__main__.Student object at 0x000001DE1223B488>
'''

↑没有实现单例,↓实现了单例

class Student:
    __isInstance = False  # 保存已经创建好的实例
    def __new__(cls, *args, **kwargs):
        #没有,则创建
        if not cls.__isInstance:
            cls.__isInstance = object.__new__(cls)
        #有,则直接返回
        return cls.__isInstance
    def __init__(self, name):  # 初始化类的实例,实例由new方法传递过来,即self。
        print('init()方法,{}'.format(name))


stu1 = Student('zhangsan')
stu2 = Student('zhang')
print(stu1)
print(stu2)
'''
输出:
init()方法,zhangsan
init()方法,zhang
<__main__.Student object at 0x000002219136B888>
<__main__.Student object at 0x000002219136B888>
'''

属性管理

在这里插入图片描述
注意类属性和实例属性的区别。
在这里插入图片描述
可以动态添加实例属性,每个对象都不同。
在这里插入图片描述
在这里插入图片描述

getatrribute

在这里插入图片描述
访问不存在的属性的异常处理方法一:
在这里插入图片描述
可实现控制台日志输出的功能:
在这里插入图片描述
设置某些属性的访问控制权限:
在__getatrribute__方法中判断

getattr

处理异常,访问不存在的属性时候被调用,访问不存在的属性的异常处理方法二。

class Student:
    address = 'china'  # 类属性

    def __init__(self, name, age):  # 实例属性
        self.name = name
        self.age = age

    def __getattr__(self, item):
        print('getattr方法调用{}'.format(item))

stu = Student('zhang', 19)
print(stu.xxx)

'''
输出:
getattr方法调用xxx
None
'''

setattr

class Student:
    def __init__(self, name, age):  # 实例属性
        self.name = name
        self.age = age

    def __setattr__(self, key, value):
        if key == 'age':
            if value < 18:
                raise Exception('age<18')
            else:
                self.__dict__['age'] = value
                #self.age = value  #不可以这么写。死循环,因为又调用了__setattr__
stu = Student('zhang', 9)

'''
输出:
Traceback (most recent call last):
...
Exception: age<18
'''

反射

在这里插入图片描述

在这里插入图片描述

  • 动态调用对应方法:hasattr
class Dog:
    def __init__(self, name):  # 实例属性
        self.name = name

    def eat(self):
        print('{} eat'.format(self.name))
    def sleep(self):
        print('{} sleep'.format(self.name))

dog = Dog('erha')
choice = input('input choice:')
if hasattr(dog, choice):
    func = getattr(dog, choice)
    func()
else:
    print('方法不存在')
  • 动态添加属性、方法
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值