简体   繁体   English

Python类-每个类都调用新ID

[英]Python classes - each class call new id

is it possible to store a class instance as a new instance. 是否可以将类实例存储为新实例。 For example, 例如,

class ClassName(object):
    def __init__(self, **kw):
         self._name = ''
         self._time = float(timeString)


         for attr, val in kw.items():
               if val == None:
                  continue
               setattr(self, '_' + attr, val)

    def getName(self): return self._name
    name = property(getName)

but lets say we store the instance in a list like so.. 但可以说我们将实例存储在这样的列表中。

cl = ClassName('name1')
cl2 = ClassName('name2')
li = list()
li.append(cl)
li.append(cl2)

and then we iterate through them.. 然后我们遍历它们。

for c in li:
    print( c.name )

would they have different values, or will it be the same, if so how can I give the class instances a unique id? 它们将具有不同的值,还是会相同,如果是的话,如何为类实例赋予唯一的ID?

If I understand what you mean, then yes: they will have different values. 如果我理解您的意思,那么是的:它们将具有不同的价值。 Fixing the problems mentioned in the comments: 解决注释中提到的问题:

class ClassName(object):
    def __init__(self, **kw):
         self._name = ''
         for attr, val in kw.items():
               if val == None:
                  continue
               setattr(self, '_' + attr, val)

    def getName(self): return self._name
    name = property(getName)

cl = ClassName(name='name1')
cl2 = ClassName(name='name2')
li = list()
li.append(cl)
li.append(cl2)

Then: 然后:

>>> li[0].name
'name1'
>>> li[1].name
'name2'

(the names you set with your keyword arguments). (您使用关键字参数设置的名称)。

Using the dictionary object that tracks a class's variables, it is possible to add and remove variables of a class. 使用跟踪类变量的字典对象,可以添加和删除类变量。

Simply pass a dictionary to the update() method of the objects built-in dictionary, __dict__ . 只需将字典传递给对象内置字典__dict__update()方法即可。 The key will be the variable name that is accessible from the class. 关键字将是可从类访问的变量名称。

class EmptyClass: 
    pass

var_name = 'new_variable'
var_value = 'This variable is a test, anything can go here'

obj = EmptyClass()
obj.__dict__.update( {var_name: var_value} )

print obj.new_variable

See the add_food() function below for a real example. 有关实际示例,请参见下面的add_food()函数。

Example

class Food:
    def __init__( self, name, description ):
        self.name = name
        self.description = description
    def __str__(self): return '<Food: name=%s, description=%s' % (self.name, self.description)


class Foods:
    def __init__( self, category, *foods ):
        self.category = category
        self.foods = {}

        if foods:
            self.add_foods( *foods )

    def add_food( self, food, update=True ):
        self.foods[food.name] = food
        if update:
            self.__dict__.update( {food.name.replace(' ', '_'): food} )

    def add_foods( self, *foods ):
        for food in foods:
            # Set update to false, so an update doesn't happen
            # more than once
            self.add_food( food, False )

        new_food = { food.name: food for food in foods }
        self.__dict__.update( new_food )

apple = Food('apple', 'Round and red')
grape = Food('grape', 'small, round and purple') 

# Our add_food() method handles removing the space and putting
# an underscore. Variables can't have spaces in them!
apple2 = Food('green apple', 'Round and green') 

fruits = Foods('fruits', apple, grape)
print fruits.apple
print fruits.grape

fruits.add_food( apple2 )
print fruits.green_apple


print
print fruits.foods['apple']
print fruits.foods['grape']
print fruits.foods['green apple']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM