[Python] Defining methods of python class in separate files [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to understand how to define methods of python classes without having to write the methods in one block of code within the class. Considering this simple example

    # methods.py

    def method(self):
    self.my_attribute += 1.


    # classes.py

    from methods import method

    class my_class:
    def __init__(self):
    self.my_attribute = 1.
    def my_method(self):
    method(self)


    #test.py

    from classes import my_class
    from methods import method
    myclass = my_class()


    is this

    myclass.my_method()


    different to this

    method(myclass)


    i.e does defining my_method within myclass as its method bring any benefit compared to calling it as function and myclass as its argument ? Especially with regard to cases where my_attribute may be very large and my_method may be called many times ?

    Continue reading...

Compartilhe esta Página