Reputation: 83
I have a class with larger methods (i.e. lots of lines of code) located in separated files as such:
├── 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")
Now I want to access the classvar
from within largemethod1
and largemethod2
. I have tried to do this with:
largemethod1.py
:
def largemethod1(self):
# Lots of lines of code
print("I am largemethod1")
print(MyClass.classvar)
But I get an NameError: name 'MyClass' is not defined
error.
What is the correct way to access the class variable from largmethod1
and largemethod2
?
Upvotes: 1
Views: 58
Reputation: 553
Not enough reputation for commenting. So:
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)
Upvotes: 1