mahmood
mahmood

Reputation: 24805

instantiating and defining classes in python

There is a python file named BasePlat.py which contain something like this:

class BasePlatform(SimObj):
  type = 'BasePlatform'
  size = Param.Int(100, "Number of entries")

class Type1(BasePlatform):
  type = 'Type1'
  cxx_class = 'Type1'

Now this file is used in another file named BaseModel.py

from BasePlat import BasePlatform
class BaseModel(ModelObj):
  type = 'BaseModel'
  delay = Param.Int(50, "delay")
  platform = Param.BasePlatform(NULL, "platform")

These file define the parameters. In another file inst.py, some models are instantiated and I can modify the parameters. For example I can define two models with different delays.

class ModelNumber1(BaseModel):
  delay = 10

class ModelNumber2(BaseModel):
  delay = 15

However I don't know how can I reach size parameter in BasePlatform. I want something like this (this is not a true code):

class ModelNumber1(BaseModel):
  delay = 10
  platform = Type1
  **platform.size = 5**

class ModelNumber2(BaseModel):
  delay = 15
  platform = Type1
  **platform.size = 8**

How can I do that?

Upvotes: 0

Views: 264

Answers (1)

StefanoP
StefanoP

Reputation: 3898

The attributes you are defining are at class level, which means that every instance of that class will share the same objects (which are instantiated at definition time).

If you want ModelNumber1 and ModelNumber2 to have different platform instances, you have to override their definition. Something like this:

class ModelNumber1(BaseModel):
  delay = 10
  platform = Param.Type1(NULL, "platform", size=5)

class ModelNumber2(BaseModel):
  delay = 15
  platform = Param.Type1(NULL, "platform", size=8)

Edit the BasePlatform class definition with something like this:

class BasePlatform(SimObj):
  type = 'BasePlatform'
  size = Param.Int(100, "Number of entries")

  def __init__(self, size=None):
    if size:
      self.size = size
      # or, if size is an integer:
      # self.size = Param.Int(size, "Number of entries")

If you don't have access to the BasePlatform definition, you can still subclass it as MyOwnBasePlatform and customize the __init__ method.

Upvotes: 2

Related Questions