Python魔法

__call__(self,[,args...]) :允许实例像函数一样执行

class Student():
    __number = 100
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __call__(self,name,age):
        print(name,age)
studentA = Student('Jack',18)
studentA("hello","world")  # studentA.__call__("hello","world")

__len__(self):实例对象被len()函数调用时,执行此函数

class Student():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __len__(self):
        print('访问实例对象的长度')
        return 100
studentA = Student('Jack',18)
print(len(studentA))

# 访问实例对象的长度
# 100

__getattr__(self,attr): 访问实例的属性不存在时,执行此函数,并将函数返回结果作为不存在属性的值

class Student():
    __number = 100
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __getattr__(self,attr):
        print(attr + "不存在")
        return '不能确定性别'
studentA = Student('Jack',18)
print(studentA.sex)
print(studentA.name)


# sex不存在
# 不能确定性别
# Jack

__getattribute__(self,attr):访问实例的属性时,不管实例的属性是否存在,都会执行该函数,函数的返回值就是属性的值

__getattribute__()执行,就不会执行__getattr__(self,attr)

class Student():
    __number = 100
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __getattr__(self,attr):
        print(attr + "不存在")
        return '不能确定性别'
    def __getattribute__(self,attr):
        print('正在访问实例的'+ attr)
        return 'man'
studentA = Student('Jack',18)
print(studentA.sex)
print(studentA.name)

# 正在访问实例的sex
# man
# 正在访问实例的name
# man

__setattr__(self,attr,value): 给实例的属性赋值的动作,就是执行该函数

class Student():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __setattr__(self,attr,value):
        print(attr,value)
        return 100
    def __getattr__(self,attr):
        print(attr + '属性不存在')
studentA = Student('Jack',18)
studentA.score = 90    # 等价于 studentA.__setattr__(self,'score',90)
print(studentA.name)

# name Jack
# age 18
# score 90
# name属性不存在
# None

 

你可能感兴趣的:(Python)