java转python记录 四

构造方法

class Man(Person):
    def __init__(self):
        Person.__init__(self)       #调用父类Person的构造方法
        super(Man, self).__init__() #super方式调用父类的构造方法,推荐使用此方法,python3中super的使用更加的super

当设计一个序列类型的类时:

__len__;__getitem__;__setitem__;__delitem__就有了自己的意义,分别在调用len(),get(),set(),del()的时候会调用对应方法

property函数的使用    需要补充

装饰器@staticmethod ,@classmethod     需要补充

__getattribute__(self,name)     当属性name被访问时会被调用

__getattr__(self,name)        当访问属性name,而属性name不存在时,才会调用

__setattr__(self,name,value)    当给属性name赋值的时候会被调用

__delattr__(self,name)    当删除属性name的时候会被调用

class Rectangle:
    def __init__(self):
        self.width = 0
        self.height = 0

    def __setattr__(self, key, value):
        if key == 'size':
            self.width,self.height = value
        else:
            self.__dict__[key] = value
            #self[key] = value  此写法是错误的 会循环调用

    def __getattr__(self, item):
        if item == 'size':
            return self.width, self.height
        else:
            raise AttributeError

__getattribute__也会导致死循环,因为他会拦截所有特性的访问,实际运用的时候需要注意

__iter__    返回一个迭代器对象    需要实践一下

扫描二维码关注公众号,回复: 1854091 查看本文章

__next__    结合迭代器使用,两个方法结合才能实现迭代器的功能    需要实践一下

生成器    任何包含yeild语句的函数称之为生成器    需要实践一下    next() 和 send()调用

with    需要结合__enter__ 和__exit__    __enter__需要提供with后面as跟着的对象

装饰器    外观类似于java中的注解,作用类似于spring的切面编程    需要实践一下

__new__    再构造对象的时候调用

 __call__    当对象被当成函数调用的时候会调用此方法

__gt__    a>b的时候

__add__    a+b时调用

__or__    a|b时调用

__str__    str(a)时调用

上一篇            下一篇

猜你喜欢

转载自blog.csdn.net/livelse/article/details/80823251