python子类定义报错:TypeError: __init__() missing 1 required positional argument: ‘prilege‘

在学习《Python编程:从入门到实践》中类这一章节,其中子类的案例代码如下:

class Car():
--snip--
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.")
class ElectricCar(Car):
"""电动汽车的独特之处"""
    def __init__(self, make, model, year):
""" 初始化父类的属性,再初始化电动汽车特有的属性
"""
        super().__init__(make, model, year) 
        self.battery = Battery()

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

于是我仿照案例写了如下代码:

class User():
    def __init__(self, first_name, last_name):
        self.fist_name = first_name
        self.last_name = last_name

    def describle(self):
        print("The uses\'s name is " + str(self.fist_name) + ' ' + str(self.last_name) + '.')

    def greet(self):
        print('Hello !' + str(self.fist_name) + ' ' + str(self.last_name) + '.')


class Privilege():
    def __init__(self, prilege):
        self.prilege = prilege

    def show_privilege(self):
        print("The privilege of the user is " + self.prilege)


class Admin(User):
    def __init__(self, first_name, last_name):
        User.__init__(self,first_name, last_name)
        self.prilege = Privilege()


people1 = Admin('hans', 'D')
people1.prilege.show_privilege()

 运行报错如下:

TypeError: __init__() missing 1 required positional argument: 'prilege'

报错原因:

定义将 类Privilege作为Admin属性 定义时没有传参!

而案例中不需要传参是因为定义 类Battery时,其类内部初始化了,没有额外参数的读入

改正后的代码如下:

class User():
    snip '''代码段同上'''

class Privilege():
    snip '''代码段同上'''


class Admin(User):
    def __init__(self, first_name, last_name,prilege):    '''读入参数:privilege'''
        User.__init__(self,first_name, last_name)
        self.prilege = Privilege(prilege)  '''此处传入''


people1 = Admin('hans', 'D','adding post')     '''加了一个'adding post'''
people1.prilege.show_privilege()

虽然引入了类的概念,但不能忘了函数调用时参数的引用、初始化,这些根本之道

你可能感兴趣的:(python,报错,python,开发语言)