我有一个更大的方法(即很多代码行)位于单独的文件中的类,如下所示:
├── 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句