我正在尝试在名为getphone的方法下设置参数role ='r'。在 init 下使用super可以正常工作,但我不知道如何在另一种方法下进行操作
角色是为正在运行的api设置权限级别
此代码有效
PATH = 'home_drive_'
PLATFORM = 'Linux_'
ITEM = '_PC'
class Credential:
def __init__(self, *, path, platform, role='', **kwargs):
super().__init__(**kwargs)
self.role = role
self.username_file = path + platform + role
class AXL(Credential):
def __init__(self, *, item, **kwargs):
super().__init__(role='rw', **kwargs)
self.item = item
def getphone(self):
self.role = 'r'
return self.username_file + self.item
def writephone(self):
self.role = 'rw'
return self.username_file + self.item
def statusphone(self):
self.role = 'rwx'
return self.username_file + self.item
reg1 = AXL(path=PATH, platform=PLATFORM, item=ITEM)
print(reg1.getphone())
print(reg1.writephone())
print(reg1.statusphone())
在AXL类下,我想将角色='r'移动到getphone方法下
我已经尝试过并且可以正常工作,但是我不明白为什么我需要放置路径和平台。
PATH = 'home_drive_'
PLATFORM = 'Linux_'
ITEM = '_PC'
class Credential:
def __init__(self, *, path, platform, role='', **kwargs):
super().__init__(**kwargs)
self.role = role
self.username_file = path + platform + role
class AXL(Credential):
def __init__(self, *, item, **kwargs):
super().__init__(**kwargs)
self.item = item
def getphone(self):
super().__init__(path=PATH, platform=PLATFORM, role='r')
return self.username_file + self.item
def writephone(self):
super().__init__(path=PATH, platform=PLATFORM, role='rw')
return self.username_file + self.item
def statusphone(self):
super().__init__(path=PATH, platform=PLATFORM, role='rwx')
return self.username_file + self.item
reg1 = AXL(path=PATH, platform=PLATFORM, item=ITEM)
print(reg1.getphone())
print(reg1.writephone())
print(reg1.statusphone())
可以找到一个沙箱here
答案 0 :(得分:1)
没有一个角色与实例相关联;相反,该角色与实例所调用的方法 相关联。试试这个。
PATH = 'home_drive_'
PLATFORM = 'Linux_'
ITEM = '_PC'
class Credential:
def __init__(self, *, path, platform, **kwargs):
super().__init__(**kwargs)
self.username_file = path + platform
class AXL(Credential):
def __init__(self, *, item, **kwargs):
super().__init__(**kwargs)
self.item = item
# "Private" method used to implement the other phone methods
# You could inline this if you want.
def _phone(self, role):
return self.username_file + role + self.item
def getphone(self):
return self._phone('r')
def writephone(self):
return self._phone('rw')
def statusphone(self):
return self._phone('rwx')
reg1 = AXL(path=PATH, platform=PLATFORM, item=ITEM)
print(reg1.getphone())
print(reg1.writephone())
print(reg1.statusphone())
答案 1 :(得分:0)
super()
将允许您访问父类范围。您可以在python3中以super().method(args)
的形式从中访问任何方法,而在python 2中,格式为super(YourClass,self).method(args)
。
从OOP角度看,在父方法上为每种方法调用__init__
似乎并不正确。您正在其父对象生命周期中对其进行初始化。如果要从父级设置角色,则只需使用self.role = ...
。父访问self.role
的任何方法都会看到修改。