3 ms·
"Instantiating an object from a name in a string. Like instantiate a 'Foo' when you have a string variable that contains 'Foo'. I can't remember the syntax even
by eesmith 8y ago
"Instantiating an object from a name in a string. Like instantiate a 'Foo' when you have a string variable that contains 'Foo'. I can't remember the syntax even though I looked it up two days ago, .."
Python doesn't have specific syntax for that. It can be as simple as:
obj = globals()["Foo"]()
That assumes "Foo" is in your global namespace. If you don't care about security then you can do:
>>> import math
>>> s = "math.cos"
>>> eval(s)(3)
-0.98999249660044542
If you care about security then you might not want to allow arbitrary objects, like "os.unlink" to be referenced. There are third-party packages which provide different models of how to get objects, like Django's "import_string" at https://docs.djangoproject.com/en/2.0/ref/utils/#django.utils.module_loading.import_string https://docs.djangoproject.com/en/2.0/ref/utils/#django.util... .
"The weird sort-of typing of variables. Variables have types,"
Variables have only one type, "reference to Python Object". An expression like 'var = "Hey " + var' may change the type of the value that var references, just like how 'var = var * 234.567' may change the type of the value that var references from an integer/long to a float, or "var = var * "Hey"', if var == 2, causes var to be a reference to the string "HeyHey".
".iteritems(). Really"
This was for a transition phase. It no longer exists in Python 3, where items() returns an iterator instead of a list.
"super(ClassName, self).__init__(argument). Wut?"
In Python 3 this is: "super().__init__(argument)", as in:
>>> class A:
... def __init__(self, s):
... print("A says", s)
...
>>> class B(A):
... def __init__(self, t):
... super().__init__(t*2)
...
>>> B("hello?")
A says hello?hello?
<__main__.B object at 0x10b201630>
"but it's still just like any other 20+ year old language in wide spread use - crufty, idiosyncratic in many respects"
A reason for the oft-bemoaned backwards-incompatible changes to Python 3 was to remove some of the crufty, idiosyncratic language features that you rightly pointed out. You are still using Python 2.7, so cannot take advantage of those changes.
- roel_v 8y agoOk the 'global' syntax thing makes a lot more sense than the one I was told about (which involved the 'inspect' module iirc). The typing - yes I understand all of that, my point still stands that it's all 'you don't need to know all of this! Oh, at least, until you do'. Wrt python3 - fair enough, things probably do get better. But that just reinforces my point about cruft building up in any practical language, and Python being just as susceptible to it as other languages.