zoukankan      html  css  js  c++  java
  • python修改类属性

    python修改类属性

    1,当类属性为不可变的值时,不可以通过实例对象去修改类属性

    class Foo(object):
        x = 1.5
    
    foo = Foo()
    print(foo.x)         #输出:1.5
    print(id(foo.x))     #输出:2400205363696
    
    foo.x = 1.7
    print(foo.x)         #输出:1.7
    print(id(foo.x))     #输出:2400203142352   和上面的id不一样,表明已经新创建了一个实例属性
    print(Foo.x)         #输出:1.5

    2,当类属性为可变的值时,可以过实例对象去修改类属性

    class Foo(object):
        x = [1,2,3]
    
    foo = Foo()
    print(foo.x)       #输出:[1, 2, 3]
    print(id(foo.x))   #输出:1999225501888
    
    foo.x[2] = 4
    print(foo.x)      #输出:[1, 2, 4]
    print(id(foo.x))  #输出:1999225501888
    print(Foo.x)      #输出:[1, 2, 4]
    
    foo.x.append(5)
    print(foo.x)      #输出:[1, 2, 4, 5]
    print(id(foo.x))  #输出:1999225501888
    print(Foo.x)      #输出:[1, 2, 4, 5]
  • 相关阅读:
    Python
    Python
    Python
    Python
    python
    python
    Python
    pure css做的pc登陆界面
    MvcAdmin功能介绍
    pure css做的手机版博客园(我自己博客)
  • 原文地址:https://www.cnblogs.com/111testing/p/13986857.html
Copyright © 2011-2022 走看看