2

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()
  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. Is my understanding correct or not?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
brian
  • 43
  • 4
  • You should look into how modules are "called". What you need is some way to ascertain that you are infact in the right directory and can do things like `from .module import my_method`. One way to do that is via `__file__`. See [this](https://stackoverflow.com/questions/9271464/what-does-the-file-variable-mean-do) for what this does. This will likely help explain what is going on with your code. – NelsonGon May 22 '22 at 22:53

2 Answers2

3

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.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • I have removed __name__=='__main__' from myclass.py. I have added __name__=='__main__': and created my_obj.my_car() in main.py. It is working fine now. Could you please check in my question section (I have modified) if it's fine now. Thank you. – brian May 22 '22 at 23:27
1

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.

d-k-bo
  • 513
  • 5
  • 12