在Python中,读取类里的变量可以通过以下几种方法:
直接访问类变量
class A:
x = 10
class B:
y = 20
a = A()
b = B()
访问类A中的变量
print(a.x) 输出:10
访问类B中的变量
print(b.y) 输出:20
通过实例访问类变量
class A:
x = 10
class B:
y = 20
a = 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.__age
def set_age(self, age): 修改私有实例属性
if age < 0:
print('年龄不能小于0')
else:
self.__age = age
age = property(get_age, set_age) 定义一个属性
xiaoming = Person()
xiaoming.age = 15
print(xiaoming.age) 输出:15
使用`inspect`模块(用于获取类中定义的所有变量):
import inspect
class Foo(object):
val = 0
def __init__(self):
self.val = 1
foo = Foo()
获取类中定义的所有变量
print(inspect.getmembers(Foo, lambda x: not x.startswith('__') and not callable(x)))
以上是几种读取Python类中变量的方法。请根据您的具体需求选择合适的方法