我尝试在类中引用一个对象变量而不在参数中传递它但是它抛出错误
class Sample:
def __init__(self):
v = []
v.append(name)
v.append(email)
s = Sample()
s.name = "xxxx"
s.email = "ss@ss.com"
print s.v
错误:
NameError: global name 'name' is not defined
我现在在对象中分配变量名称如何在类中调用它而不向函数添加参数
答案 0 :(得分:1)
如果你绝对必须避免属性:
class Sample:
def __init__(self):
self.v = []
def addName(self, name):
self.v.append(name)
def addEmail(self, email):
self.v.append(email)
s = Sample()
s.addName("xxxx")
s.addEmail("abc@def.com")
print(s.v)
答案 1 :(得分:1)
另一种方法是使用装饰器和@property
:
class Sample(object):
def __init__(self):
self.v = [None, None]
@property
def name(self):
return self.v[0]
@property
def email(self):
return self.v[1]
@name.setter
def name(self, value):
self.v[0] = value
@email.setter
def email(self, value):
self.v[1] = value
s = Sample()
s.name = "xxxx"
s.email = "ss@ss.com"
print s.v
注意:
object
才能使其正常工作@property
装饰的方法正在作为&#34; getters&#34;并返回一个值@<name>.setter
是一个负责设置<name>
成员的setter方法,因此@email.setter
设置电子邮件,并在调用x.email = ...
时调用以上可能有点啰嗦,但允许使用干净的API来隐藏用户的详细信息......有些人确实喜欢添加get/set_name
方法以更明确,但上面更加pythonic
答案 2 :(得分:0)
如果您的要求是动态的,您可以在运行时创建属性,如
class Sample:
pass
s = Sample()
setattr(s,"name","chanda")
setattr(s,"email","xyz@gmail.com")
setattr(s,"v",[s.name,s.email])
print(s.name) #chanda
print(s.email) #xyz@gmail.com
print(s.v) #['chanda', 'xyz@gmail.com']
print(s.__dict__) #{'email': 'xyz@gmail.com', 'v': ['chanda', 'xyz@gmail.com'], 'name': 'chanda'}