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.
global variables, classes, imports
|
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. but if you want to assign a new value to a variable ... interesting that self.foo = 1 can create a new attribute in a class instance but setattr() is needed in other cases.
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Mar-02-2017, 04:29 AM
(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? you cannot add a new attribute using the first form, except for methods.
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Mar-02-2017, 05:06 AM
(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 >>>
Mar-02-2017, 08:37 AM
Mar-02-2017, 11:05 PM
forum_import.py:
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness. Recommended Tutorials: BBCode, functions, classes, text adventures |
|