Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print function prints twice a field from a class

I am using the print function to print a field from a class from another python module and it prints the field twice.

I have two modules:

main.py:

from statics import RiskyCars

class Car:
    def __init__(self, name):
        self.name = name

# init
RiskyCars()
print(RiskyCars.risky_cars[0].name)

statics.py:

class RiskyCars:

    @staticmethod
    def __init__():
        from main import Car
        RiskyCars.risky_cars = []
        RiskyCars.risky_cars.append(Car("car1"))

When I run main.py it print twice:

C:\Python27\python.exe C:/Users/myuser/PycharmProjects/Project1/main.py
car1
car1

But if I put breakpoint before the print function:

# main.py
# init
RiskyCars()     <--- break point

and then run manually from the terminal:

print(RiskyCars.risky_cars[0].name)

it prints only one time.

Why it happens ?

like image 727
E235 Avatar asked Jan 03 '23 02:01

E235


1 Answers

Python renames the primary script you run main for you as __main__. What happens is that you run main (called __main__) which runs RiskyCars.__init__ which in turn imports main (called main). Hence the script main runs twice.

The solution is to rewrite main.py to be

from statics import RiskyCars

if __name__ == '__main__':  # only execute if run as main script
    # init
    risky_car_1 = RiskyCars()  # lets at least pretend this is sensible
    print(RiskyCars.risky_cars[0].name)

statics.py to

from cars import Car

class RiskyCars:
    risky_cars = []
    def __init__(self):
        RiskyCars.risky_cars.append(Car("car1"))

and make a new file called cars.py

class Car:
    def __init__(self, name):
        self.name = name
like image 117
FHTMitchell Avatar answered Jan 06 '23 02:01

FHTMitchell