您的位置:首页技术文章
文章详情页

Python之关于类变量的两种赋值区别详解

浏览:3日期:2022-08-02 14:35:15

我就废话不多说了,还是直接看代码吧!

# -*- coding:utf-8 -*-#面试题,写一个方法,将一行字符串中所有的单词数量统计出来 class Person(object): TAG = 'hello' p1 = Person()p2 = Person() print p1.TAG #第一种赋值方式print p2.TAGprint Person.TAG #第二种赋值方式 p1.TAG = 'damn it' print p1.TAGprint p2.TAGprint Person.TAG

输出结果:可以看到,只有p1的TAG,被赋值成了新的'damn it'

hellohellohellodamn ithellohello

如何将所有对象引用的类变量都赋值成同一个值呢?

Person.TAG = 'damn it'

输出结果:完美解决问题

hellohellohellodamn itdamn itdamn it

补充知识:python类,赋值,命名空间

python中的类相当于一个命名空间,object.attr 就是一个向上爬属性的过程

属性:__dict__ , __class__ , __bases__

__dict__: 实例或类或模块的属性 , __class__ 实例对应的类对象,__bases__(元组):父类/超类

爬属性:

def findAttr(obj , attr): if attr in obj.__dict__: return obj.__dict__[attr] cls = obj.__class__ if attr in cls.__dict__: return cls.__dict__[attr] for super_cls in cls.__bases__: if attr in super_cls.__dict__: return super_cls.__dict__[attr] return None

爬类:

def classTree(cls,indent): print(’.’*indent + cls.__name__) for super_cls in cls.__bases__: classTree(super_cls,indent+4)

赋值方式:

class Test: static_var = 1 #类属性相当与C++静态成员变量 def assign(self): self.x = 1 #对象属性赋值 t = Test()t.x = 2 #也可以这样 ,直接赋值t.__dict__[’x’] = 3 #也可以这样 , __dict__是对象空间词典,每个对象一份,类对象/模块也有Test.add_static_var = 5 #也可以样新增一个类属性

类方法调用 , 常用的方式object.method() ,在python中扩展 Class.method(object) ,两者相同

Test.assign(t) print(t.x)

当object.method() 时,object被传入method(self)中的第一个参数.Class.method(object) 需要手动传入

命名空间:

x = 0def print_global(): print(x) #打印全局def print_local(): x = 1 print(x) #本地变量class A: x = 2 #类属性==C++静态成员变量 , print A.x def m(self): x = 3 #本地变量 self.x = 4 #对象属性

def change_global(): global x #修改全局变量,否则x = 100 ,是增加一个本地变量 x = 100def print_enclosing(): x = 200 def nested(): print(x) #在闭包中引用本地变量def change_in_enclosing(): x = 1 def nested(): nonlocal x x = 2 #在闭包中改变本地变量, 如没有nonlocal x , 在又新增一个本地变量

以上这篇Python之关于类变量的两种赋值区别详解别就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Python 编程
相关文章: