简体   繁体   中英

How can I add type annotation for the attribute that is dynamically assigned to a class?

Assume I have an existing class like below.

class Animal:

  name: str

  def __init__(self, name: str) -> None:
    self.name = name

  def get_name(self) -> str:
    return self.name

And in another class, I assign another attribute to this class.

class Type:
  """Another class that is dynamically assigned to one of Animal attributes."""

class TestCase:

  animal: Animal

  def __init__(self, name: str) -> None:
    self.animal = Animal(name)
    self.animal.type = Type()

How can I make a type annotation to let TestCase class knowing about animal.type: Type ?

You should extend your Animal class to define the type attribute

class TypedAnimal(Animal):

    _type: Type

class TestCase:

  animal: Animal

  def __init__(self, name: str) -> None:
    self.animal = TypedAnimal(name)
    self.animal._type = Type()

Note, type is a builtin, so it is better not to use it in your code as an identifier of an attribute. You could use _type instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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