0

Does Python have the equivalent of PHP's $this->{$var}?

Something like self.{var name}?

StephenTG
  • 2,579
  • 6
  • 26
  • 36
Rami Dabain
  • 4,709
  • 12
  • 62
  • 106
  • 1
    Do you mean you don't know the name of the attribute until runtime, or something else? – Wooble Feb 10 '14 at 17:56
  • 3
    There is no question here. – aldo Feb 10 '14 at 17:56
  • getattr and setattr are what i needed, because i don't know the name of the attribute until runtime as in first comment. – Rami Dabain Feb 10 '14 at 17:59
  • @aldo, the question is simple as "what code in python does the same as this code in php" . cheers for the ones who up-voted your comment. – Rami Dabain Feb 10 '14 at 18:00
  • 4
    When writing a question that asks "does language X have this feature from language Y," it is always helpful to explain what the feature does. Otherwise you're limiting the pool of people who can answer your question to those who know both languages involved. In fact, why not just ask how to do what you want to do, and leave language Y out of it entirely? – kindall Feb 10 '14 at 18:02
  • 1
    In addition, most of the times you use `getattr`, what you *really* want to use is a dict. `getattr` is very often a sign of bad design, unless you're writing a metaprogramming lib. – Max Noel Feb 10 '14 at 18:04

2 Answers2

4

To look up an attribute not known until runtime, use getattr:

getattr(self, "varname")

From the docs:

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

To add an attribute to an object, the counterpart is setattr:

setattr(self, "varname", value)
mhlester
  • 22,781
  • 10
  • 52
  • 75
2

You can use getattr

getattr( self, var_name )

where var_name is a string variable containing name of your field.

lejlot
  • 64,777
  • 8
  • 131
  • 164