How do I access Class member variables in Python?(如何在Python中访问类成员变量?)
本文介绍了如何在Python中访问类成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Example(object):
def the_example(self):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
如何访问类的变量?我已尝试添加此定义:
def return_itsProblem(self):
return itsProblem
然而,这也失败了。
推荐答案
几句话就是答案
在您的示例中,itsProblem是一个局部变量。
必须使用self设置和获取实例变量。您可以在__init__方法中设置它。则您的代码将为:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
但如果您想要一个真正的类变量,则直接使用类名:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)
但要小心这个变量,因为theExample.itsProblem会自动设置为等于Example.itsProblem,但它根本不是同一个变量,可以单独更改。
部分说明
在Python中,可以动态创建变量。因此,您可以执行以下操作:
class Example(object):
pass
Example.itsProblem = "problem"
e = Example()
e.itsSecondProblem = "problem"
print Example.itsProblem == e.itsSecondProblem
打印
True
因此,这正是您对前面的示例所做的操作。
确实,在Python中,我们将self用作this,但它远不止于此。self是任何对象方法的第一个参数,因为第一个参数始终是对象引用。无论您是否称之为self,这都是自动的。
这意味着您可以:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
或:
class Example(object):
def __init__(my_super_self):
my_super_self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
完全一样。任何对象方法的第一个参数都是当前对象,我们仅将其称为self作为约定。您只需向此对象添加一个变量,与从外部添加变量的方式相同。
现在,关于类变量。
当您这样做时:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
您会注意到,我们首先设置一个类变量,然后访问一个对象(实例)变量。我们从未设置过此对象变量,但它可以工作,这怎么可能?
嗯,Python试图首先获取对象变量,但如果它找不到它,就会给您提供类变量。警告:类变量在实例之间共享,而对象变量不共享。 总而言之,永远不要使用类变量来设置对象变量的默认值。为此使用__init__。
最终,您将了解到,Python类是实例,因此是对象本身,这为理解上述内容提供了新的见解。一旦你意识到这一点,请稍后再来阅读这篇文章。
这篇关于如何在Python中访问类成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:如何在Python中访问类成员变量?
基础教程推荐
猜你喜欢
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
