Python 如何在Groovy中设置对象的属性
我想用Groovy编写与此Python代码等效的代码:Python 如何在Groovy中设置对象的属性,python,groovy,Python,Groovy,我想用Groovy编写与此Python代码等效的代码: >>> class A(object): pass >>> a = A() >>> name = os.name >>> setattr(a, name, "some text") >>> a <__main__.A object at 0x10aad6a10> >>> a.posix 'value' 但它抛出一个异常
>>> class A(object): pass
>>> a = A()
>>> name = os.name
>>> setattr(a, name, "some text")
>>> a
<__main__.A object at 0x10aad6a10>
>>> a.posix
'value'
但它抛出一个异常,表示找不到该属性
编辑:我更新了代码,以反映属性/属性名称不是文字的事实。您可以执行以下操作:
class Student {
private int StudentID;
private String StudentName;
void setStudentID(int pID) {
StudentID = pID;
}
void setStudentName(String pName) {
StudentName = pName;
}
int getStudentID() {
return this.StudentID;
}
String getStudentName() {
return this.StudentName;
}
static void main(String[] args) {
Student st = new Student();
st.setStudentID(1);
st.setStudentName("Joe");
println(st.getStudentID());
println(st.getStudentName());
}
}
您需要将
name
作为String
类型的实例变量。此外,还需要声明setter和getter方法来设置和获取属性。您可以执行以下操作:
class Student {
private int StudentID;
private String StudentName;
void setStudentID(int pID) {
StudentID = pID;
}
void setStudentName(String pName) {
StudentName = pName;
}
int getStudentID() {
return this.StudentID;
}
String getStudentName() {
return this.StudentName;
}
static void main(String[] args) {
Student st = new Student();
st.setStudentID(1);
st.setStudentName("Joe");
println(st.getStudentID());
println(st.getStudentName());
}
}
class TmpClass {}
def tmp = new TmpClass()
tmp.metaClass.name = "value"
您需要将
name
作为String
类型的实例变量。此外,您还需要声明setter和getter方法来设置和获取属性。如果您只是在寻找一种设置动态属性的方法,那么方括号符号就足够了:
class TmpClass {}
def tmp = new TmpClass()
tmp.metaClass.name = "value"
tmp['name'] = 'value'
tmp[propertyName] = propertyValue //runtime property name and value
但是,如果您还需要使用新字段等动态增长对象,并且不想使用简单的映射,那么您可能应该使用(而不是类),它支持添加动态属性和闭包:
def tmp = new Expando()
tmp['name'] = 'value'
tmp[propertyName] = propertyValue //runtime values
如果您只是在寻找一种设置动态属性的方法,那么方括号符号就足够了:
tmp['name'] = 'value'
tmp[propertyName] = propertyValue //runtime property name and value
但是,如果您还需要使用新字段等动态增长对象,并且不想使用简单的映射,那么您可能应该使用(而不是类),它支持添加动态属性和闭包:
def tmp = new Expando()
tmp['name'] = 'value'
tmp[propertyName] = propertyValue //runtime values
你想添加一个新的属性吗?简单的回答是我不确定!我想稍后在代码中将“name”引用为tmp.name。“名称”和“值”是来自外部数据的字符串。是否尝试添加新属性?简单的回答是我不确定!我想稍后在代码中将“name”引用为tmp.name。“name”和“value”是来自外部数据的字符串。是的,类似于这样,但是使用name作为字符串变量?name属性的类型由赋值推断。在本例中,它是一个字符串,是的。请在我编辑的问题中查看我的getNameFromSomeWhere()函数,这会让事情更清楚。它是字符串中属性的名称。是的,类似这样,但名称是字符串变量?通过赋值推断“name”属性的类型。在本例中,它是一个字符串,是的。请在我编辑的问题中查看我的getNameFromSomeWhere()函数,这会让事情更清楚。它是字符串中属性的名称。因此,当使用Expando时,我更喜欢tmp.setProperty(),它做同样的事情,但更清晰,但似乎Expando是我最终想要的。Python代码从一个空白对象开始并添加到其中似乎没有简单的等价物。遗憾的是我掉进了玩元类的兔子洞。我会接受这个答案。所以当使用Expando时,我更喜欢tmp.setProperty(),它做同样的事情,但更清晰,但似乎Expando是我最终想要的。Python代码从一个空白对象开始并添加到其中似乎没有简单的等价物。遗憾的是我掉进了玩元类的兔子洞。我会接受这个答案。