Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中为嵌套类分配变量_Python_Python 3.x - Fatal编程技术网

如何在python中为嵌套类分配变量

如何在python中为嵌套类分配变量,python,python-3.x,Python,Python 3.x,如何为一个外部类的嵌套类赋值 例如,假设我们有这个内部类 class animal(NamedTuple) class dog(NamedTuple) name: str weight: int class cat(NamedTuple) color: str name: str 我想在下面的另一个地方初始化它,但它不编译 AnimalDic=动物(狗(name=“snoopy”,weight=“10”)、猫(color=“b

如何为一个外部类的嵌套类赋值

例如,假设我们有这个内部类

class animal(NamedTuple)
   class dog(NamedTuple)
       name: str
       weight: int
   class cat(NamedTuple)
       color: str
       name: str
我想在下面的另一个地方初始化它,但它不编译

AnimalDic=动物(狗(name=“snoopy”,weight=“10”)、猫(color=“black”,name=“tom”)


有什么方法可以实现吗?

不要嵌套它们。请先定义两个“内部”类:

class Dog(NamedTuple):
    name: str
    weight: int

class Cat(NamedTuple):
    color: str
    name: str

class Animal(NamedTuple): 
    dog: Dog
    cat: Cat

AnimalDic = Animal(Dog(name="snoopy", weight="10"), Cat(color="black", name="tom")

我还修复了您的大小写。不要使用小写作为类名。

这可能不像您认为的那样有效。它没有什么意义。不清楚这应该实现什么。根据经验,没有“嵌套类”这样的东西更准确地说,在Python中,通常没有理由使用嵌套类。Java让它们绕过“每个文件一个类”的限制,而Python没有这样的限制。