0

Suppose I have a project in ~/app/, containing at least files myclass.py, myobject.py, and app.py.

In myclass.py I have something like

def myclass():
    # class attributes and methods...

In myobject.py, I have something like

from app import myclass
attribute1 = 1
attribute2 = 2
myobject = myclass(attribute1, attribute2)

Finally, app.py looks something like

from app import myobject
# do stuff with myobject

In practice, I'm using myobject.py to gather a common instance of myclass and make it easily importable, so I don't have to define all the attributes separately. My question is on the convention of myobject.py. Is this okay or is there something that would be better to achieve the purpose mentioned. The concerns I thought of is that there are all these other variables (in this case attribute1 and attribute2) which are just... there... in the myobject module. It just feels a little weird because these aren't things that would ever be accessed individually, but the fact that it is accessible... I feel like there's some other conventional way to do this. Is this perfectly fine, or am I right to have concerns (if so, how to fix it)?

Edit: To make it more clear, here is an example: I have a Camera class which stores the properties of the lens and CCD and such (like in myclass.py). So users are able to define different cameras and use them in the application. However, I want to allow them to have some preset cameras, thus I define objects of the Camera class that are specific to certain cameras I know are common to use for this application (like in myobject.py). So when they run the application, they can just import these preset cameras (as Camera objects) (like in app.py). How should these preset objects be written, if how it's written in myobject.py is not the best way?

Zachary
  • 47
  • 5

2 Answers2

0

enter image description here

so you this method fails to call function inside the class in first case. i think you do it by making a class of attribute and getting variables from it.

class Attribute():
     def __init(self,a1,a2):
         self.a1=a1
         self.a2=a2
att=Attribute(1,2)
print(att.a1)
0

It looks like you stumbled upon the singleton pattern. Essentially, your class should only ever have one instance at any time, most likely to store global configurations or some similar purpose. In Java, you'd implement this pattern by making the constructor private, and have a static method (eg. getInstance()) that returns a private static instance.

For Python, it's actually quite tricky to implement singletons. You can see some discussion about that subject here. To me how you're doing it is probably the simplest way to do it, and although it doesn't strictly enforce the singleton constraint, it's probably better for a small project than adding a ton of complexity like metaclasses to make 'true' singletons.

Mach_Zero
  • 504
  • 3
  • 10