'How to call local variable outside of function using OOP in Python?

I know there's multiple ways of calling a variable outside of a function, but I'm trying to do this using OOP. Here's my code:

import re
import os.path as p
import sys
from contextlib import contextmanager
import os

def main(file_in):

    v_pat = re.compile(r"^v\s[\s\S]*")
    vertices = ['None']
        
    with open(file_in, 'r') as f_in:
        for line in f_in:
            v = v_pat.match(line)

            if v:
                vertices.append(v.group())

if __name__ == '__main__':
    file_in = sys.argv[1]
    main(file_in)

I'd like to call the vertices array outside of the function using OOP. What would my code look like if I were to implement that?



Solution 1:[1]

I am not sure why you don't want to return the list, but if you just want to make that function into a class and have that list as an attribute you can try this

import re
import os.path as p
import sys
from contextlib import contextmanager
import os

class MyClass:
    def __init__(self):
        self.v_pat = re.compile(r"^v\s[\s\S]*")
        self.vertices = ['None']
    def doStuff(self, file_in):
        with open(file_in, 'r') as f_in:
            for line in f_in:
                v = self.v_pat.match(line)
                if v:
                    self.vertices.append(v.group())


if __name__ == '__main__':
    file_in = sys.argv[1]
    myClass = MyClass()
    myClass.doStuff(file_in)
    print(myClass.vertices)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hello