zoukankan      html  css  js  c++  java
  • 【Python】类属性和实例属性的差异

    (本文是我自己的理解)

    类属性: class本身和实例化的对象都有

    实例属性: 只有实例化的对象有,class本身(未实例化之前)是没有的

    理由:

    类属性直接写于class下,例如

    class A():
        attr1 = "I'm class attr1"
    
    print(A.attr1)
    print(dir(A))
    
    '''
    I'm class attr1
    ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
    'attr1']
    '''

    实例属性需要前缀, 例如

    class A():
        def __init__(self):
            self.attr2 = "I'm attr2"

    在实例化一个对象的时候,第一个调用的是构造函数__new__, 然后在调用__init__初始化对象

    class A():
        def __new__(cls, *args, **kwargs):
            """do something"""
            print("I'm new")
            return super(A, cls).__new__(cls, *args, **kwargs)
    
        def __init__(self, *args, **kwargs):
            print("I'm init")
            #do something
            self.attr1 = 'attr1'
    
    a = A()
    # I'm new
    # I'm init

    如果__new__不返回父级的__new__方法(最上层当然是object),就不会调用__init__

    class A():
        def __new__(cls, *args, **kwargs):
            """do something"""
            print("I'm new")
            # return super(A, cls).__new__(cls, *args, **kwargs)
    
        def __init__(self, *args, **kwargs):
            print("I'm init")
            #do something
            self.attr1 = 'attr1'
    
    a = A()
    # I'm new

    在对象没有实例化的时候,是没有self这一说的..所以依靠self生成的函数都不存在。

    所以实例属性不会在类中,只会在实例中,而类属性可以在实例中

    class A():
        attr1 = "I'm attr1"
        def __init__(self):
            self.attr2 = "I'm attr2"
    
    
    print(A.attr1) # I'm attr1
    print(A.attr2) # AttributeError: type object 'A' has no attribute 'attr2'
    print(dir(A)) #['__class__', '__new__'... '__weakref__', 'attr1']
    a = A()
    print(a.attr1) # I'm attr1
    print(a.attr2) # I'm attr2
    print(dir(a)) #['__class__', ...'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'attr1', 'attr2']
  • 相关阅读:
    URAL 2015 Zhenya moves from the dormitory(水题)
    概率DP总结(待整理)
    HDU 5236 Article(概率DP+贪心 待解决)
    2015上海邀请赛
    树链剖分(待整理)
    hust 5239 Doom(线段树 规律OR数论 待整理 )
    Java大数BigInteger BigDecimal
    hdu 5505 GT and numbers
    hdu 5532 Almost Sorted Array
    hdu 5533 Dancing Stars on Me
  • 原文地址:https://www.cnblogs.com/Hed-geh0g/p/8525588.html
Copyright © 2011-2022 走看看