Python遇到的代码错误:TypeError: __init__() missing 1 required positional argument: ‘priviledges‘

时间:2024-03-23 18:29:34

Python遇到的代码错误:TypeError: init() missing 1 required positional argument: ‘priviledges’

这是在学习python中遇到的一个问题,是关于类的参数问题,说到底还是对类的知识没理解透。。。
代码简略看一下。。。
我用的是spyder编辑器

源码

class User():
def init(self,first_name,last_name,user_gender,user_age):
self.first_name = first_name
self.last_name = last_name
self.user_gender = user_gender
self.user_age = user_age
self.login_attempts = 0
def describe_user(self):
u_info = {}
full_name = self.first_name+self.last_name
u_info[‘full_name’] = full_name
u_info[‘age’] = self.user_age
u_info[‘gender’] = self.user_gender
print(u_info)
def greet_user(self):
if self.user_gender ‘female’:
print(“Hello,”+self.first_name+“女士.”)
elif self.user_gender
’male’:
print(“Hello,”+self.first_name+“先生.”)
else:
print(“性别无法识别”)
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0

class Admin(User):
def init(self,first_name,last_name,user_gender,user_age):
super().init(first_name,last_name,user_gender,user_age)
self.priviledge = Priviledges()
def greet_user(self):
print(“Hello,”+self.first_name+“管理.”)

class Priviledges():
def init(self,priviledges = [‘can add post’,‘can del’,‘can ban’]):
self.priviledges = priviledges
def show_priviledges(self):
print(“The admin’s functions:”)
for priviledge in self.priviledges:
print(priviledge)

这样调用就不报错

Python遇到的代码错误:TypeError: __init__() missing 1 required positional argument: ‘priviledges‘

报错代码

Python遇到的代码错误:TypeError: __init__() missing 1 required positional argument: ‘priviledges‘
报错提示
Python遇到的代码错误:TypeError: __init__() missing 1 required positional argument: ‘priviledges‘

原因分析

向别人请教后,大佬说了一句参数的问题,给的类里没有初始化参数,这才想到我既然调用这个类了,没有给它传参还想着让他自己生成,有点拉闸。之后感觉又可以将代码这样写(只对Admin()和Priviledges()类进行了修改)
class Admin(User):
def init(self,first_name,last_name,user_gender,user_age):
super().init(first_name,last_name,user_gender,user_age)
self.priviledge = Priviledges([‘can add post’,‘can del’,‘can ban’])
def greet_user(self):
print(“Hello,”+self.first_name+“管理.”)

class Priviledges():
def init(self,priviledges):
self.priviledges = priviledges

def show_priviledges(self):
print(“The admin’s functions:”)
for priviledge in self.priviledges:
print(priviledge)

这样写的意思是直接在Admin类里调用的时候直接给值,也能成功运行,还是懂的太少了哈哈