I have a class that maps a database object
class MyObj:
def __init__(self):
...SQL request with id as key...
if len(rows) == 1:
...maps columns as my_obj attributes...
self.exists = True
else:
self.exists = False
With such design, an object is created each time, and we check if it is present in database with .exists attribute.
my_obj = MyObj(id=15)
if my_obj.exists:
...do stuff...
It works.
But I suspect there is a cleaner way to init, and we would just have to check like that:
my_obj = MyObj(id=15)
if my_obj:
...do stuff...
Simply put the functions in a separate module (. py file) and put your variables in the module scope (e.g. global variables) - that's the pythonic way to do what you want if you do not need thread safety.
But in Python, it is not compulsory that the parent class constructor will always be called first. The order in which the __init__ method is called for a parent or a child class can be modified.
The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.
__new__ is static class method, while __init__ is instance method. __new__ has to create the instance first, so __init__ can initialize it. Note that __init__ takes self as parameter. Until you create instance there is no self . Now, I gather, that you're trying to implement singleton pattern in Python.
You can't do this in __init__
, because that method is run after the new instance is created.
You can do it with object.__new__()
however, this is run to create the instance in the first place. Because it is normally supposed to return that new instance, you could also choose to return something else (like None
).
You could use it like this:
class MyObj:
def __new__(cls, id):
# ...SQL request with id as key...
if not rows:
# no rows, so no data. Return `None`.
return None
# create a new instance and set attributes on it
instance = super().__new__(cls) # empty instance
instance.rows = ...
return instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With