+ 1
How to create decorators?
Please go through the code: https://code.sololearn.com/coFLokNQt0Vj/?ref=app everything is in the comments.
14 Antworten
0
Hmm.. I found 2 ways to make your code work, also it should be "os.system('clear')" in linux(Sololearn) not 'cls';
- 1st method:
When defining cls function add os argument then in decorator inner func call cls(os) after importing it
- 2nd method: (a bit hacky)
After importing os add this line:
globals()["os"] = os
* I think the problem that it imports os and stores it locally just in the decorator
+ 2
Sousou
it is "cls" as I wrote it in my windows
+ 2
Sousou
thank you!
it works and not works (because it's linux)
can you explain the line?
globals() ["os"] = os
+ 1
Harsha S it's fine then.
+ 1
Harsha S np :)
globals is a function that returns global variables in dict, but it's a bit dangerous to use it, you can use it to access global variables, edit them, add, remove, etc..
You can try: print(globals())
it's like: vars and locals
I used it to make os module as a global variable named "os"
+ 1
Sousou
why is it dangerous?
+ 1
Harsha S 🤔
Not sure.. maybe, because you can access and change global variables everywhere in your code, but I think it's not dangerous while it's a module.
+ 1
I didn't very well understand your code but a decorator is required to return a function.
So change 'return inner()' to 'return inner'
+ 1
abhinav
i had changed but forgot to save
+ 1
It is hacky, using decorator to do the import. And as suggested by Sousou you have to declare os as a global in your decorator, so not very elegant. And 'cls' is specific to Windows, so I changed it to 'clear' to make it work when I tried it in Pydroid on my Android phone. Also Sololearn could not cleanly do the clear console command and produced some strange characters instead. But you hack does work.
i called the decorated cls() first, then cls2() with the normal import os below to compare the result. Modifications are commented with capital letters.
Here is your code with modifications. You should change 'clear' back to 'cls' if you try it on Windows.
https://code.sololearn.com/cfphbxKMZvOQ/?ref=app
0
?!
- 1
Bob_Li thank you
- 2
idk