Feb-19-2017, 04:37 AM
In Python, anytime a variable is referenced, it will be looked for in the local scope, then enclosing scope, up to global. Methods are no different than functions in this way.
(Feb-19-2017, 04:37 AM)micseydel Wrote: [ -> ]In Python, anytime a variable is referenced, it will be looked for in the local scope, then enclosing scope, up to global. Methods are no different than functions in this way.
self.foo = 1
can create a new attribute in a class instance but setattr() is needed in other cases.(Feb-26-2017, 03:28 AM)Skaperen Wrote: [ -> ]interesting that self.foo = 1 can create a new attribute in a class instance but setattr() is needed in other cases.What do you mean?
self.foo = 1
setattr(self, foo, 1)
(Feb-26-2017, 09:49 AM)buran Wrote: [ -> ](Feb-26-2017, 03:28 AM)Skaperen Wrote: [ -> ]interesting that self.foo = 1 can create a new attribute in a class instance but setattr() is needed in other cases.What do you mean?
self.foo = 1
and
setattr(self, foo, 1)
would yield the same result
(Mar-02-2017, 04:29 AM)Skaperen Wrote: [ -> ]you cannot add a new attribute using the first form, except for methods.What are you going on about?
>>> class Blank: ... pass ... >>> a = Blank() >>> a <__main__.Blank instance at 0x02B12760> >>> a.foo Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Blank instance has no attribute 'foo' >>> a.foo = 5 >>> a.foo 5 >>>
(Feb-26-2017, 09:49 AM)buran Wrote: [ -> ]setattr(self, foo, 1)
setattr(self, 'foo', 1)
EGG = 'eggses' class Egg(object): def __init__(self, style): self.style = style egg = Egg('scrambled') egg.scrapple = 'bacon'forum_test.py:
from forum_import import * HAM = 'hocks' class Spam(object): def __init__(self, spice): self.spice = spice def test(self): print(self.spice) if hasattr(self, 'ham'): print(self.ham) print(HAM) print(EGG) print(egg.style) print(egg.scrapple) spam = Spam('garlic') spam.ham = 'Wilbur' spam.test()The output of running forum_test.py:
garlic Wilbur hocks eggses scrambled baconCorrect me if I'm wrong, but doesn't this cover everything you're talking about? If you are defining something like HAM, and your Spam instance can't see it, there is some other problem going on. It's not a namespace issue.