在运行时更改类变量? [英] Changing Class Variables in runtime?

查看:141
本文介绍了在运行时更改类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我想想我想做什么:我有一个结构或类叫 student ,其中包含

Let me give an idea of what I wish to do: I have a structure or class called student, which contains variables like

int roll_no

int reg_no

如果用户希望在运行时添加一个新变量,例如 char name ,那么如何做呢?

If the user wishes to add a new variable like char name at run time how can it be done?

推荐答案

基于单词Structure和变量声明,我要猜这个问题是关于C的一些风味。如何确定将取决于语言,但作为一般规则,如果语言被编译(例如C / C ++,Java),这是不可能的。如果语言被解释(例如Python),这可能是可能的,像这样:

Based on the word "Structure" and the variable declarations, I'm going to guess this question is about some flavor of C. How exactly to do this will depend on the language, but as a general rule, if the language is compiled (e.g. C/C++, Java), this is not possible. If the language is interpreted (e.g. Python), this might sort of be possible, like this:

class MyObj:
  message = "Hi there"

a = MyObj()  # Creating a new instance variable
a.name = "Bill" # Adding a new attribute

这里我们将 name 属性添加到 a 仅限对象 ,而不是整个类。我不知道你是怎么走这一切的整个班。

Here we've added the name attribute to the a object only, and not the entire class. I'm not sure how you're go about that for the whole class.

但真的,你的问题的答案是不要。你应该考虑你的程序和你使用的对象足以知道你会和不需要什么字段。如果你想在程序的某个点有一个名字字段,把它放在类声明中。如果你不希望它在对象创建上有一个值,使用一个合理的默认值,如 null

But really, the answer to your question is "Don't". You should think about your program and the objects you're using enough to know what fields you will and won't need. If you'll want to have a name field at some point in your program, put it in the class declaration. If you don't want it to have a value on object creation, use a sensible default like null.

根据您的意见,有几种方法来处理。我还不完全清楚你想要什么,但我认为这些情况之一应该覆盖它。在我知道的语言中,Python在运行时是最灵活的:

Based on your comments, there are a couple of ways to approach this. I'm still not entirely clear on what you want, but I think one of these cases should cover it. Of the languages I know, Python is the most flexible at runtime:

只是另一种对象。类变量(请参见此问题)属于类本身,并继承您创建的任何实例:

In Python, a class is just another kind of object. Class variables (check out this question too) belong to the class itself, and are inherited by any instances you create:

class MyObj:
  a = 2            # A class variable
  b = "a string"   # Another one

ObjInstance = MyObj()  # Creating an instance of this class
print ObjInstance.a  # Output: "2"    
ObjInstance.a = 3  # You can access and change the value of class variables *for this instance*    
print MyObj.a, ObjInstance.a  # Outputs "2 3".  We've changed the value of a for the instance

MyObj.c = (3,4)  # You can add a new class variable at runtime    
# Any instance objects inherit the new variable, whether they already exist or not.
print MyObj.c, ObjInstance.c  # Outputs "(3, 4) (3, 4)"

您可以使用它向类的每个实例添加属性,但它们都将具有相同的值,直到您更改它们。如果您想要为一个实例添加属性,可以这样做:

You can use this to add attributes to every instance of your class, but they will all have the same value until you change them. If you want to add an attribute to just one instance, you can do this:

ObjInstance.d = "I belong to ObjInstance!"
print ObjInstance.d   # Output: "I belong to ObjInstance!"
print MyObj.d  # Throws "AttributeError: class MyObj has no attribute 'd'"

使用Python的一个缺点是它可能有点慢。如果你想使用编译的语言,它会稍微复杂一些,并且很难获得我上面提到的相同的功能。但是,我认为这是可行的。这里是我将在Java做它。在C / C ++中的实现将有所不同。

One drawback to using Python is that it can be kinda slow. If you want to use a compiled language it will be slightly more complicated, and it will be harder to get the same functionality that I mentioned above. However, I think it's doable. Here's how I would do it in Java. The implementation in C/C++ will be somewhat different.

Java的类属性调用(和声明) static

Java's class attributes (and methods) are called (and declared) static:

class MyObj {
  public static int a = 2;
  public static String b = "a string";
}

static 变量通常通过类名访问,如在Python中。您可以通过实例获得他们,但我相信会生成警告:

static variables are normally accessed through the class name, as in Python. You can get at them through an instance, but I believe that generates a warning:

System.out.println(MyObj.a);   //Outputs "2"
MyObj ObjInst = new MyObj();
System.out.println(ObjInst.a);  //Outputs "2" with a warning.  Probably.

您不能在运行时向Java对象添加属性:

You can't add attributes to a Java object at runtime:

ObjInst.c = "This will break";  // Throws some exception or other

但是,可以有一个 HashMap 属性, static ,你可以在运行时添加条目,就像属性一样。 (这正是Python在后台的作用。)例如:

However, you can have a HashMap attribute, static or not, which you can add entries to at runtime that act like attributes. (This is exactly what Python does, behind the scenes.) For example:

class MyObj {
  private HashMap<String, Object> att = new HashMap<String, Object>();

  public void setAttribute(String name, Object value) {
    att.put(name, value);
  }

  public Object getAttribute(String name) {
    return att.get(name);
  }     
}

然后你可以这样做:

ObjInst.setAttribute("name", "Joe");
System.out.println(ObjInst.getAttribute("name"));

注意我没有声明 att code> static 上面,因此在这种情况下, MyObj 类中的每个实例都有此属性,类本身不会。如果我已经声明它 static ,类本身将有一个这个散列的副本。如果你想真的想,你可以结合这两种情况:

Notice that I did not declare att static above, so in this case each instance of the MyObj class has this attribute, but the class itself does not. If I had declared it static, the class itself would have one copy of this hash. If you want to get really fancy, you can combine the two cases:

class MyObj {
  private static HashMap<String, Object> classAtt = new HashMap<String, Object>();
  private HashMap<String, Object> instAtt = new HashMap<String, Object>();

  public static void setClassAttribute(String name, Object value) {
    classAtt.put(name, value);
  }

  public void setInstAttribute(String name, Object value) {
    instAtt.put(name, value);
  }

  public Object getAttribute(String name) {
    // Check if this instance has the attribute first
    if (this.instAtt.containsKey(name) {  
      return instAtt.get(name);
    }
    // Get the class value if not
    else {
      return classAtt.get(name);
    }
  }     
}

out,像处理 HashMap 没有你要求的值的情况,但你可以找出在那里做什么。最后一点,你可以在Python中,我在这里用一个 dict ,这可能是一个好主意,如果属性名称将是字符串。你可以添加一个属性作为字符串

There are a few details I've left out, like handling the case of the HashMaps not having the value you're asking for, but you can figure out what to do there. As one last note, you can do in Python exactly what I did here in Java with a dict, and that might be a good idea if the attribute names will be strings. You can add an attribute as a string in Python but it's kind of hard; look at the documentation on reflection for more info.

祝你好运!

这篇关于在运行时更改类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆