I am learning python and have acquired basic knowledge. However, I was doing my own practice using 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()
1-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.
2-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:
Instance a Python object from another Python file
Why I cannot import a function from a class in python?
I am really curious and want to know the concept. I would kindly request you to please let me know if my understanding is correct or not. Thank you.