When does a name search happen, and when not?

Python in a nutshell

class B(object):
  def f(self): return 23
  g = property(f)
class C(B):
  def f(self): return 42
c = C()
print(c.g)                # prints: 23, not 42

... the property does not search for this name , but uses the function object that it passed at creation time.

If you need to work around this problem, you can always do this by adding an additional search level:

class B(object):
  def f(self): return 23
  def _f_getter(self): return self.f()
  g = property(_f_getter)
class C(B):
  def f(self): return 42
c = C()
print(c.g)                # prints: 42, as expected

Here, the function object held by this property is B._f_getter, which in turn searches for the name f (since it calls self.f ()) ;

What does search mean?

Under what conditions does a “search” take place?

What is the rule that determines that a property does not perform a search, but self.f()does?

Thank.

+4
source share
1 answer

"" " , ". , , .

, property(f), , B. , f . f , obj.g, f ( ).

, property(_f_getter), - , _f_getter - . _f_getter , obj.g, _f_getter . , _f_getter self ( self.f).

, : " ". , , , , . , , , .

+4
source

Source: https://habr.com/ru/post/1680252/


All Articles