pytho basic programming: pycharm implemented without adding a parent class attributes subclass

This article describes the pycharm add a parent class does not implement the property in a subclass, a good reference value, we want to help. Xiao Bian together to follow up to see it
I ado, directly or look at the code it!

class Car():
  """一次模拟汽车的简单尝试"""
  def __init__(self, make, model, year):
    """初始化描述汽车的属性"""
    self.make = make
    self.model = model
    self.year = year
    self.odometer_reading = 0
 
  def get_description_name(self):
    """返回整洁的描述性信息"""
    long_name = str(self.year) + ' ' + self.make + ' ' + self.model
    return long_name.title()
 
  def read_odometer(self):
    """打印一条指出汽车里程的消息"""
    print("This car has " + str(self.odometer_reading) + " miles on it.")
 
  def update_odometer(self, mileage):
    """
    将里程读数设置为指定的值
    禁止将里程表读数往回调
    """
    if mileage >= self.odometer_reading:
      self.odometer_reading = mileage
    else:
      print("You can't roll back an odometer!")
 
  def increment_odometer(self, miles):
    """将里程表读数增加指定的量"""
    self.odometer_reading += miles
 
 
class ElectricCar(Car):
  """电动汽车的独特之处"""
  def _init_(self, make, model, year):
    """
    电动汽车的独特之处
    初始化父类的属性,再初始化电动汽车特有的属性
    """
    super().__init__(make, model, year)
    self.battery_size = 70
 
  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_description_name())
my_tesla.describe_battery()

operation result:

Traceback (most recent call last):
 File "E:/Python编程从入门到精通配套资料/Self-taught Python/electric_car.py", line 50, in <module>
  my_tesla.describe_battery()
 File "E:/Python编程从入门到精通配套资料/Self-taught Python/electric_car.py", line 46, in describe_battery
  print("This car has a " + str(self.battery_size) + "-kwh battery.")
AttributeError: 'ElectricCar' object has no attribute 'battery_size'

Additional knowledge: python class inheritance, methods of adding subclass covers methods of subclasses, adding attributes of the subclass, and continue to the parent class attributes

a python subclass method if we want to inherit a class and do not change the current class, we can create, to continue his method

1, class inheritance, let's create a parent class Animal, and let us create a subclass of a dog, inherited from the parent class's method dog Animal subclasses, but there's no execute any code, then we initialize the subclass about dog as dog_1, remember there is also the incoming height weight, or will be error we can find dog_1 inherits the properties and methods Animal inside. Direct output and what to call it.

class Animal():
  def __init__(self, weight, high):
    self.weight = weight
    self.high = high
  def shout(self):
    print('wow')
class Dog(Animal):
  pass
dog_1 = Dog(20,40)
print(dog_1.high)
print(dog_1.weight)
dog_1.shout()
#输出内容是
40
20
wow

2, a method for adding a subclass, we can also add new methods in this sub-class dog, for example, we add a run method, and then initialize it dog_1, you will find dog_1 will have run this method.

class Dog(Animal):
  def run(self):
    print('running')
dog_1 = Dog(20,40)
dog_1.run()
#输出结果是
running

3, covering the method of subclass, we add a subclass Cat, also inherited Animal, but you find that Cat is not a wow so called, so we have to redefine what shout function, the parent class Animal in the function overwritten. Then we call the initialization cat_1 Cat subclass, remember to pass weight and height, or will be error, and then call shout method, you will find the contents of the output is miao, because the subclass of functions in the parent class functions overwritten a.

class Cat(Animal):
  def shout(self):
    print('miao')
cat_1 = Cat(20, 40)
cat_1.shout()
#输出结果是
miao

4, add an attribute of the subclass, and continue properties of the parent class, then if we give Cat add a property color, with the same __init__ to define the properties, but we have to use super () to inherit the parent class weight and sexual high, color attributes, the same with self.color assignment, so we cat_2 Cat class initialization time will pass three parameters, we output a cat_2.color, you can see a normal call.

class Cat(Animal):
  def __init__(self, weight, high, color):
    super().__init__(weight, high)
    self.color = color
  def shout(self):
    print('miao')
cat_2 = Cat(20, 40, 'yellow')
print(cat_2.color)
#输出结果是
yellow

Class inheritance will stop here,
content on more than how many, and finally to recommend a good reputation in the number of public institutions [programmers], there are a lot of old-timers learning skills, learning experience, interview skills, workplace experience and other share, the more we carefully prepared the zero-based introductory information, information on actual projects, the timing has to explain the Python programmer technology every day, share some learning methods and the need to pay attention to small detailsHere Insert Picture Description

Published 20 original articles · won praise 0 · Views 3618

Guess you like

Origin blog.csdn.net/chengxun02/article/details/104998753
Recommended