python - Is there a way to access the properties of a class created in one function from another function? -
is there way access properties of class created in 1 function function ?
class component(object): name = '' num = 100 def __setattr__(self, name, value): object.__setattr__(self, name, value) def one(): exec('aaa' + '=component()') aaa.name = 'aaa' aaa.num = aaa.num * 2 print '1', aaa.name, aaa.num def two(): print '2', aaa.name, aaa.num one() two()
i "nameerror: global name 'aaa' not defined"
class level attributes belong class , therefore shared among instances of class.
if want different instances of class have different name
, num
attributes (by way, should using lowercased attribute names instances), should add them instance attributes. can access class attributes using class name (e.g. component.num
).
class component(object): name = '' num = 100 def __init__(self, name, num): self.name = name self.num = num print component.name # '' print component.num # 100 c = component('aaa', component.num * 2) print c.name # 'aaa' print c.num # 200
Comments
Post a Comment