However, I was doing my own Python practice using the datetime module and got confused with the below line datetime.now()
.
from datetime import datetime
now = datetime.now()
I know that datetime
is a class and now()
is a method but what I am confused about is that should we not use an object to call the method? Or is it a static
/class
method which is usually called by classname.method
?
I tried to mimic the same by creating a module, class and tried calling it from another module so that I can only import object of the class in another module and call the methods like object.method()
but I am unable to import object in another module.
I have two python files myclass.py and main.py and both are in same directory.
# myclass.py
class MyClass:
def __init__(self, brand):
self.brand = brand
def my_car(self):
print(f'this is {self.brand} new car')
my_obj = MyClass("BMW")
Now from main.py
# main.py
from myclass import my_obj
if __name__ == '__main__':
my_obj.my_car()
Can someone please guide me how
datetime.now()
is being called? Is it being called using class method approach (class.method
) or is it being called using datetime object (object.method
). I am just curious and trying to understand the concept behind it.Is it possible to import only object from another module? I read couple of links on stackoverflow which are as following but I am confused:
I am really curious and want to know the concept. Is my understanding correct or not?