在Python中,读取类里的变量可以通过以下几种方法:
直接访问类变量
class A:x = 10class B:y = 20a = A()b = B()访问类A中的变量print(a.x) 输出:10访问类B中的变量print(b.y) 输出:20
通过实例访问类变量
class A:x = 10class B:y = 20a = A()b = B()通过实例访问类A中的变量print(a.x) 输出:10通过实例访问类B中的变量print(b.y) 输出:20
使用`property`装饰器(用于属性函数):

class Person(object):def __init__(self):self.__age = 18 定义一个私有化属性def get_age(self): 访问私有实例属性return self.__agedef set_age(self, age): 修改私有实例属性if age < 0:print('年龄不能小于0')else:self.__age = ageage = property(get_age, set_age) 定义一个属性xiaoming = Person()xiaoming.age = 15print(xiaoming.age) 输出:15
使用`inspect`模块(用于获取类中定义的所有变量):
import inspectclass Foo(object):val = 0def __init__(self):self.val = 1foo = Foo()获取类中定义的所有变量print(inspect.getmembers(Foo, lambda x: not x.startswith('__') and not callable(x)))
以上是几种读取Python类中变量的方法。请根据您的具体需求选择合适的方法
