码迷,mamicode.com
首页 > 编程语言 > 详细

【Python】类属性和实例属性的差异

时间:2018-03-08 00:15:58      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:div   self   getattr   返回   some   orm   weak   mat   tee   

(本文是我自己的理解)

类属性: 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‘]

 

【Python】类属性和实例属性的差异

标签:div   self   getattr   返回   some   orm   weak   mat   tee   

原文地址:https://www.cnblogs.com/Hed-geh0g/p/8525588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!