1005663861 发表于 2022-3-7 22:51:39

关于类的调用问题

from class_examples1 import Car


class ElectricCar(Car):
    def __init__(self, make, model, year):
      super().__init__(make, model, year)
      self.battery = Battery


class Battery:
    def __init__(self, battery_size=70):
      self.battery_size = battery_size

    def describe_battery(self):
      print('This car has a ' + str(self.battery_size) + '-kWh battery')


my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery().describe_battery()


这里的20行中my_tesla.battery().describe_battery()的,my_tesla.battery后边为什么需要加括号,如果是my_tesla.battery.describe_battery()则会报错,请问这是为什么?

publicwhore 发表于 2022-3-7 23:00:50

self.battery = Battery改成self.battery = Battery()

isdkz 发表于 2022-3-7 23:01:57

因为在类中定义的方法默认是实例方法,实例方法只有实例调用才会自动传入 self,

而 battery 你赋值为了 Battery 类,还没有实例化,

你可以把代码改成这样:
from class_examples1 import Car


class ElectricCar(Car):
    def __init__(self, make, model, year):
      super().__init__(make, model, year)
      self.battery = Battery()                                 # 这里加括号,后面就不用加括号


class Battery:
    def __init__(self, battery_size=70):
      self.battery_size = battery_size

    def describe_battery(self):
      print('This car has a ' + str(self.battery_size) + '-kWh battery')


my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()                                  # 这里不加括号
页: [1]
查看完整版本: 关于类的调用问题