设为首页 收藏本站
查看: 635|回复: 0

[经验分享] python Object And Class

[复制链接]

尚未签到

发表于 2017-4-25 12:03:53 | 显示全部楼层 |阅读模式
  python Object And Class

1:在Python中每一个都是对象,class 是一个对象,class的实例也是一个对象。在java或者c++中,class 是不用来存放数据的,只有class的实例才存放
    数据
    class class1(object):
    pass

if __name__=='__main__':
    test = class1()
    print class1
    print test
 
 class1是一个对象,print 出来的结果:<class '__main__.class1'>
 那么 test也是一个对象,test.__class__也是一个对象
 
2:在python中所有的对象允许动态的添加属性或者方法,当类添加属性之后,类的实例同样能够访问该对象,
    如果修改了类的__class__的属性或者方法,那么该类对性的实例同样也具有该类的方法或者属性
    class class1(object):
    pass

    if __name__=='__main__':
    test = class1()
    #print class1
    #print test
   
    test.__class__.newAttr=10
    test1 = class1()
    print test1.newAttr
   
    当我们通过test.__class__修改了class1类的属性之后,给class1添加了个新的属性newAttr=10
    则重新test = class1()新的实例后,新的实例拥有newAttr这个属性,
    对于添加新的方法同样如此
   
  3:每个实例都有__dict__来存放动态的属性,查看一下代码:
      class class1(object):
        pass

        if __name__=='__main__':
        test = class1()
        #print class1
        #print test
       
        test.__class__.newAttr=10
        test1 = class1()
        print test.__dict__
        print test.__class__.__dict__
        print test1.__dict__
        print test1.__class__.__dict__
        test1.newAttr2=20
        print test.__dict__
        print test.__class__.__dict__
        print test1.__dict__
        print test1.__class__.__dict__
       
    4:继承:当继承后,python不会向java,c++那样在子类的实例中包含父类的实例,子类的实例是个全新的对象,与父类一点关系都没有,
        不会包含有父类的任何东西,继承只是在子类的__base__指向了父类,在查找函数,属性的过程中会查找父类,
        仅此而已,而这个父类也是class对象
       
    5:类里的变量不是以self,开头定义的都是类变量,相当于java,c++里的static,所有实例共享他们
   
    6:python为每一个对象定义了一些属性和方法
        __doc__
        __module__
        __class__
        __bases__
        __dict__
       
    7:python的继承
        基类 __init__ / __del__ 需显示调用
        继承方法的调用和基类声明顺序有关
        在成员名称前添加 "__" 使其成为私有成员。
        除了静态(类型)字段,我们还可以定义静态方法。
        class Class1:
          @staticmethod
          def test():
            print "static method"
   
            Class1.test()
            static method
           
            从设计的角度,或许更希望用属性(property)来代替字段(field)。
                 class Class1:
                  def __init__(self):
                    self.__i = 1234
                  def getI(self): return self.__i
                  def setI(self, value): self.__i = value
                  def delI(self): del self.__i
                  I = property(getI, setI, delI, "Property I")
                 
                 a = Class1()
                 a.I
                1234
                 a.I = 123456
                 a.I
                123456
               
                如果只是 readonly property,还可以用另外一种方式。
                 class Class1:
                  def __init__(self):
                    self.__i = 1234 
                  @property
                  def I(self):
                    return self.__i
                 
                 a = Class1()
                 a.I
                1234
               
                -----------------------
               
                用 __getitem__ 和 __setitem__ 可以实现 C# 索引器的功能。
                 class Class1:
                  def __init__(self):
                    self.__x = ["a", "b", "c"]
                  def __getitem__(self, key):
                    return self.__x[key]
                  def __setitem__(self, key, value):
                    self.__x[key] = value
               
                   
                 a = Class1()
                 a[1]
                'b'
                 a[1] = "xxxx"
                 a[1]
                        'xxxx'
                 
               
                 
       
    8:python的多重继承
        由于python的继承主要是将几个对象建立关系,因此多重继承最重要的就是怎样在多个父类中寻找某个attribute
        python寻找attribute的顺序:  
        1. If attrname is a Python-provided attribute for objectname, return it.
       2. Check objectname.__class__.__dict__ for attrname. If it exists and is a data-descriptor, return the descriptor result. Search all bases of objectname.__class__ for the same case.
       3. Check objectname.__dict__ for attrname, and return if found. Unless objectname is a type object, in which case search its bases too. If it is a type object and a descriptor is found in the object or its bases, return the descriptor result.
       4. Check objectname.__class__.__dict__ for attrname. If it exists and is a non-data descriptor, return the descriptor result. If it exists, and is not a descriptor, just return it. If it exists and is a data descriptor, we shouldn't be here because we would have returned at point 2. Search all bases of objectname.__class__ for same case.
       5. Raise AttributeError



    9:python重载
        我们还可以通过重载 __getattr__ 和 __setattr__ 来拦截对成员的访问,需要注意的是 __getattr__ 只有在访问不存在的成员时才会被调用。
        >>> class Class1:
          def __getattr__(self, name):
            print "__getattr__"
            return None
          def __setattr__(self, name, value):
            print "__setattr__"
            self.__dict__[name] = value
       
           
        >>> a = Class1()
        >>> a.x
        __getattr__
        >>> a.x = 123
        __setattr__
        >>> a.x
        123
       
        如果类型继承自 object,我们可以使用 __getattribute__ 来拦截所有(包括不存在的成员)的获取操作。
        注意在 __getattribute__ 中不要使用 "return self.__dict__[name]" 来返回结果,因为在访问 "self.__dict__" 时同样会被 __getattribute__ 拦截,从而造成无限递归形成死循环。
        >>> class Class1(object):
          def __getattribute__(self, name):
            print "__getattribute__"
            return object.__getattribute__(self, name)
       
         
        >>> a = Class1()
        >>> a.x
        __getattribute__
       
        Traceback (most recent call last):
         File "<pyshell#3>", line 1, in <module>
         a.x
         File "<pyshell#1>", line 4, in __getattribute__
         return object.__getattribute__(self, name)
        AttributeError: 'Class1' object has no attribute 'x'
        >>> a.x = 123
        >>> a.x
        __getattribute__
        123

       

   
   

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-369109-1-1.html 上篇帖子: Ruby和Python的语法差别 下篇帖子: python 搜索 PDF文件 内容
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表