python - 从 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
从内部访问largemethod1
和largemethod2
。我试图这样做:
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)
推荐阅读
- reactjs - jsx 函数中使用的括号渲染和卷曲
- android - 将数据发布到 RESTful-webservice - 为什么此代码在 Eclipse 中有效,但在 android 中无效?
- php - 我无法使用从 .txt 获得的数据连接到数据库
- javascript - javascript - 将按钮单击的处理推迟到页面加载后
- java - 如何从子类更改父类中变量的值?
- scala - 如何在scala中使用高阶函数计算列表的阶乘
- .net-core - 如何在 Visual Studio Mac 中为 NuGet 设置本地/远程源
- ios - 外键约束在 sqlite3 Objc 中不起作用
- pine-script - 请帮助我使用 pinescript 中的以下代码
- python - python:运行'nohup':如何摆脱消息?