如何用另一个类的实例作为属性实例化一个类?

时间:2020-01-11 22:09:29

标签: python python-3.x class instantiation

我正在尝试自己学习Python。 我有以下代码片段:

Java

是否可以在Tank类的class Car(): def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.tank = Tank() class Tank(): def __init__(self, *args, **kwargs): self.tank_size = kwargs.get('tank_size', None) def describe_tank(self): print("This car has a " + str(self.tank_size) + "-L tank.") 中不为参数tank_size指定默认值的情况下实例化Car? 谢谢。 附言对代码进行一些编辑以使其更具逻辑性。

3 个答案:

答案 0 :(得分:3)

我认为您可以尝试通过kwargs.get访问它,并在那里提供默认值。

    def __init__(self, *args, **kwargs):
        self.tank_size = kwargs.get('tank_size', None)

所以现在您可以将tank_size传递给Car构造函数,再传递给Tank的构造函数。如果仍然不想使用默认值,则可以再次通过kwargs传递它。

    def __init__(self, make, model, year, **kwargs):
        self.make = make
        self.model = model
        self.year = year

        self.tank = Tank(**kwargs)

所以就像

class Car():
    def __init__(self, make, model, year, **kwargs):
        self.make = make
        self.model = model
        self.year = year

        self.tank = Tank(**kwargs)

class Tank():
    def __init__(self, *args, **kwargs):
        self.tank_size = kwargs.get('tank_size', None)

    def describe_tank(self):
        if self.tank_size:
            print("This car has a " + str(self.tank_size) + "-L tank.")
        else:
            print("No info about the tank.")



car = Car("bmw", "m5", 2000)
car.tank.describe_tank()

new_car = Car("bmw", "m5", 2000, tank_size=3)
new_car.tank.describe_tank()

答案 1 :(得分:0)

您可以尝试这样做,但是此解决方案将限制您扩展Tank类的输入,以后您必须手动处理所有其他属性。

class Tank():
    def __init__(self, *args,**kwargs):
        if args:           
            self.tank_size = args[0]
        else:
            self.tank_size = "Not Specified"

    def describe_battery(self):
        print("This car has a {}-L tank.".format(self.tank_size))

对于字符串格式,我也建议使用.format内置函数。

答案 2 :(得分:0)

您始终可以将其保留为属性,并将其从初始化参数中删除。

class Car():

    def __init__(self, make, model, year):
        self.tank = Tank()


class Tank():

    def __init__(self):
        self.tank_size = None

    def set_tank_size(self, size):
        self.tank_size = size

    def describe_battery(self):
        print("This car has a " + str(self.tank_size) + "-L tank.")

或者,如果您想正确执行操作,可以使用属性和设置器。

from number import Real


class Car():

    def __init__(self, make, model, year):
        self.tank = Tank()


class Tank():

    def __init__(self):
        self._tank_size = None

    @property
    def tank_size(self):
        return self._tank_size

    @tank_size.setter
    def tank_size(self, size):
        if not isinstance(size, Real):
            raise TypeError('Tank `size` must be a number.')
        if not size >= 0:
            raise ValueError('Tank `size` must be >= 0.') # electrics have a 0-L tank?
        self._tank_size = size

    def describe_battery(self):
        print("This car has a " + str(self.tank_size) + "-L tank.")