从位于 Python 中单独文件中的方法访问类变量

马克

我有一个更大的方法(即很多代码行)位于单独的文件中的类,如下所示:

├── myclass
│   ├── largemethod1.py
│   ├── largemethod2.py
│   ├── __init__.py

__init__.py

class MyClass:
    classvar = "I am the class variable."

    from .largemethod1 import largemethod1
    from .largemethod2 import largemethod2

    def smallmethod(self):
        print("I am the small method")

largemethod1.py

def largemethod1(self):
   # Lots of lines of code
   print("I am largemethod1")

largemethod2.py

def largemethod2(self):
   # Lots of lines of code
   print("I am largemethod2")

现在我想classvar从内部largemethod1largemethod2. 我试图这样做:

largemethod1.py

def largemethod1(self):
   # Lots of lines of code
   print("I am largemethod1")
   print(MyClass.classvar)

但我得到一个NameError: name 'MyClass' is not defined错误。

largmethod1访问类变量的正确方法是什么largemethod2

毕托克拉底

没有足够的声誉发表评论。所以:

def largemethod2(self):
   # Lots of lines of code
   print("I am largemethod2")
   print(self.classvar)


# No need for class instantiation because cls is our class.
@classmethod
def clargemethod2(cls):
   # Lots of lines of code
   print("I am clargemethod2")
   print(cls.classvar)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 bash for 循环从位于子目录中的单独文件运行 Python doctest

在python中的单独类中访问单独方法上的列表

使数字在Python中位于一行

在Python中,如何获取位于模块内文件目录的路径

执行位于子文件夹中的 python 代码

代码不再位于单独的文件中

在方法中访问类变量的方法 - python

Python Plotly-Dash从清单中删除“内联”,因此项目位于单独的行上

从单独模块中的类访问方法时的Python循环导入

如何在 Flutter 中位于单独 dart 文件中的文本小部件内定义变量

是否可以读取位于 python 项目中的 csv 文件?

Python 3.7.2文件夹不能位于/ Library / Python中

使用位于单独类中的 ->GetString(" ") 时出现段错误

如何通过位于单独类中的引用传递矢量

如何在Python的类方法中访问“静态”类变量?

Mac上的Python中的Selenium-Geckodriver可执行文件必须位于PATH中

如何增加位于python中另一个文件中的数字

尝试读取与 python 文件位于同一目录中的文件但收到 FileNotFoundError

加载位于 MainWindow.xaml 内的单独文件中的资源

显示并更新位于单独文件中的AsyncTask对话框

如何从子文件夹访问文件,该子文件夹位于最近使用python创建或修改的文件夹中?

在Selenium / Python中出现错误-chromedriver可执行文件必须位于PATH中

当测试文件位于其他模块中时,Python无法找到测试

如何导入位于pycharm项目中相同子目录中的python文件

使用Python的Selenium-Geckodriver可执行文件必须位于PATH中

从python打开位于远程服务器中的文件时出错

Python Selenium错误:“ WebDriverException:'login'可执行文件必须位于PATH中。”

在位于Google驱动器中的数据库文件上运行python脚本

如何将位于文件中的列表转换为我可以在 python 中使用的列表?