Home > front end >  Python - understanding from datetime import datetime module
Python - understanding from datetime import datetime module

Time:05-23

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.

CodePudding user response:

datetime.now() is a classmethod.

Your import doesn't work because of this:

if __name__ == '__main__':
    my_obj = MyClass("BMW")
    my_obj.my_car()

The entire purpose of the if statement is to determine if the module is being imported, or is being executed directly.

If the module is being imported, __name__ is not equal to "__main__", and thus my_obj does not exist.

CodePudding user response:

Take a look at the datetime source code:

class datetime(date):
    ...

    @classmethod
    def now(cls, tz=None):
        "Construct a datetime from time.time() and optional time zone info."
        t = _time.time()
        return cls.fromtimestamp(t, tz)

The @classmethod decorator creates a class method. It implicitly passes the class as a first argument.

This approach is often used as an alternative constructor such as

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

    @classmethod
    def from_dict(cls, d):
        return cls(d["brand"])  # or cls(**d)
from cars import Car

car_description = {"brand": "DeLorean"}

car = Car.from_dict(car_description)

Note: The class method has no self reference. In this example, the class hasn't even been instantiated yet.

  • Related