tree get_info get_info ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-38.pyc │ └── get_resources.cpython-38.pyc └── get_resources.py contents of get_resources.py
class get_resource_info(): def __init__(self): self.color = 'red' def print(self): print("hi printing") print(self.color) I have the following file test.pyhere:
#!/usr/bin/env python from get_info import get_resource_info class test(): def __init__(self): pass def test(self): get_resource_info.print(self) if __name__ == '__main__': tes = test() tes.test() from above structure, I do not understand the following: when I run test.py - I get the following output:
hi printing Traceback (most recent call last): File "./test.py", line 17, in <module> tes.test() File "./test.py", line 9, in test get_resource_info.print(self) File "/get_info/get_resources.py", line 14, in print print(self.color) AttributeError: 'test' object has no attribute 'color' couple of things that are not making sense to me:
- when I call the get_resource_info.print module from get_resource_info object why do i have to pass an argument (self)
- i dont understand why it is complaining that there is no attribute color -- my understanding is, when I call the object get_resource_info, it will first initiate the
__init__module and set its attributes!! , in this case it should have set the attribute color
please let me know what I am understanding wrong here. will appreciate any help I can get.
i have looked at this: Importing class from another file to make __init__.py work
I have also looked at: Python: How to access property from another file ? from file name import class didn't work
and other resources but I am not able to figure it out unfortunately, so please let me know what is going on here!!
Prabin
get_resource_info.print(self)on the class get_resource_info and not an instance. Instances, liketes.test()will pass themself as the first argument. On a class there is no automatic insertion of a first argument.get_resource_info().print() # this will work2) Now you passselftoget_resource_info.print,selfat that position in the tes object, which has no color attribute, likewise theget_resource_infoclass has not - only instances of it.print(self, type(self))might help you to further track down what's going on.os, we call its methods byos.walk, we dont doos().walk(). So why is this the case for those library! it may be a stupid question, and sorry for that.get_info{module}.get_resource_info(){class}likewiseos{module}.walk(){function}oros{module}.PathLike(){class}python allows us to drop the module prefix via imports. Hope this helps