如何创建一个类来检查它是否在特定类的签名内实例化?

问题描述 投票:0回答:1

我需要创建一个类,它可以检查实例化的范围。它只能在特定类的签名内实例化

class Fish:
    pass

class Water:
    def __init__(self, animal):
        pass

habitat = Water(Fish()) # this should work

class Land:
    def __init__(self, animal):
        pass

habitat = Land(Fish()) # this should not be allowed
fish = Fish() # this also cannot be allowed
python class oop
1个回答
0
投票

如果你想确保 a

Fish
只允许与
Water
一起使用,那么我会反转关系,将
Water
实例传递给
Fish
构造函数,并在构造函数内部验证这确实是一个
Water
实例。即,

class Water:
    pass

class Fish:
    def __init__(self, habitat):
        if not isinstance(habitat, Water):
            raise ValueError("no water for the fish")
        self.habitat = habitat

animal = Fish(Water()) # this works

class Land:
    pass

animal = Fish(Land()) # raises ValueError: no water for the fish
fish = Fish() # raise TypeError: Fish.__init__() missing 1 required positional argument: 'habitat'

这样鱼就有了栖息地。无论如何,这对我来说似乎更符合逻辑, 因为反过来说,一个栖息地只会有(单一)鱼,而不是有大量的动物和动物(和植物)物种。

© www.soinside.com 2019 - 2024. All rights reserved.