通过实例访问类变量
class A:
x = 10
a = A()
print(a.x) 输出:10
通过类名直接访问类变量
class A:
x = 10
print(A.x) 输出:10
通过类的`__dict__`属性访问类变量
class A:
x = 10
print(A.__dict__['x']) 输出:10
将类转换为字典
class A:
x = 10
a = A()
print(dict(a)) 输出:{'__module__': '__main__', '__doc__': None, '__dict__': , '__weakref__': , 'x': 10}
使用`vars()`函数
class A:
x = 10
print(vars(a)) 输出:{'__module__': '__main__', '__doc__': None, '__dict__': , '__weakref__': , 'x': 10}
使用`dir()`函数
class A:
x = 10
print(dir(a)) 输出:['__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__', 'x']
使用`getattr()`和`setattr()`函数
class A:
x = 10
print(getattr(a, 'x')) 输出:10
setattr(a, 'x', 20)
print(a.x) 输出:20
使用`inspect`模块
import inspect
class A:
x = 10
print(inspect.getmembers(A, lambda m: not m.startswith('__') and not m.endswith('__'))) 输出:[('x', 10)]
以上方法可以帮助你访问Python类中的变量。需要注意的是,类变量与实例变量是不同的,类变量是属于类的,所有实例共享同一个类变量,而实例变量是每个实例独有的。