首页 > 解决方案 > 从 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

标签: python

解决方案


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

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)

推荐阅读