Python学习第二十课——自定property and classmethod

自定制property

class Lazyproperty:
    def __init__(self,func):
        # print('==========>',func)
        self.func=func
    def __get__(self, instance, owner):
        print('get')
        # print(instance)
        # print(owner)
        if instance is None:
            return self
        res=self.func(instance)
        setattr(instance,self.func.__name__,res)
        return res
    # def __set__(self, instance, value):
    #     pass

class Room:
    def __init__(self,name,width,length):
        self.name=name
        self.width=width
        self.length=length
    # @property #area=property(area)
    @Lazyproperty  #area=Lazypropery(area)
    def area(self):
        return self.width * self.length
    @property  #test=property(test)
    def area1(self):
        return  self.width * self.length
# print(Room.__dict__)
r1=Room('厕所',1,1)
# print(r1.__dict__)

#实例调用
# print(r1.area)
# print(Room.__dict__)

#类调用
# print(Room.area)

# print(r1.test)
# print(Room.test)
# print(r1.area1)
# print(r1.area1)
# print(r1.area1)
# print(r1.area1)

print(r1.area)
print(r1.__dict__)

print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)

自定制classmethod

class ClassMethod:
    def __init__(self,func):
        self.func=func
    def __get__(self, instance, owner): #类来调用,instance为None,owner为类本身,实例来调用,instance为实例,owner为类本身,
        def feedback(*args,**kwargs):
            print('在这里可以加功能啊...')
            return self.func(owner,*args,**kwargs)
        return feedback

class People:
    name='linhaifeng'
    @ClassMethod # say_hi=ClassMethod(say_hi)
    def say_hi(cls,msg,x):
        print('你好啊,帅哥 %s %s %s' %(cls.name,msg,x))

People.say_hi('你是那偷心的贼',10)

p1=People()
p1.say_hi('你是那偷心的贼',10)

自定制元类

class MyType(type):
    def __init__(self,a,b,c):
        print('元类的构造函数执行')
        # print(a)
        # print(b)
        # print(c)
    def __call__(self, *args, **kwargs):
        # print('=-======>')
        # print(self)
        # print(args,kwargs)
        obj=object.__new__(self) #object.__new__(Foo)-->f1
        self.__init__(obj,*args,**kwargs)  #Foo.__init__(f1,*arg,**kwargs)
        return obj
class Foo(metaclass=MyType): #Foo=MyType(Foo,'Foo',(),{})---》__init__
    def __init__(self,name):
        self.name=name #f1.name=name
# print(Foo)
# f1=Foo('alex')
# print(f1)

f1=Foo('alex')
print(f1)
print(f1.__dict__)
原文地址:https://www.cnblogs.com/pyhan/p/12326349.html