, , . ".py", , - , , , " ".
, , - inspect.currentframe - "f_lineno", , ( __init__). inspect.filename .
, "=", , , .
from inspect import currentframe, getfile
class A(object):
def __init__(self):
f = currentframe(1)
filename = getfile(f)
code_line = open(filename).readlines()[f.f_lineno - 1]
assigned_variable = code_line.split("=")[0].strip()
print assigned_variable
my_name = A()
other_name = A()
, , assignemtn, , , for, , -
, .
Botton line: , - -
, , , collections.namedtuple
" ", , - , , :
class A(object):
def __init__(self, name):
self.name = name
x = A("x")
, , - .
- Python , "=", , . , statemtns, Python, for, with, def class. , , specfically , , "" .
Focus on the instructions def. It usually creates a function. But with the help of a decorator, you can use "def" to create any object - and the name used for the function available to the constructor:
class MyObject(object):
def __new__(cls, func):
self = object.__new__(cls)
self.name = func.func_name
return self
def __init__(self, func):
print "My name is ", self.name
@MyObject
def my_name(): pass
(This last way to do this can be used in production code, unlike the one that resorts to reading the source file)