python 父子属性访问?

python 父子属性访问?

from loguru import logger

class State:

def __init__(self):

self.logger = logger

def __setattr__(self, name, value):

self.logger.info(f'wwwwasdasd')# 问题代码

self.__dict__[name] = value

class LocalState(State):

def __init__(self):

super().__init__()

self.ll = 2

if __name__ == '__main__':

state = LocalState()

state.ll = 22222

print(state.ll)

怎么可以让这个 self.logger 属于子类(不是直接添加到子类属性这种方式),并且可以运行


回答:

from loguru import logger

class State:

def __setattr__(self, name, value):

if hasattr(self, 'logger'):

self.logger.info(f'wwwwasdasd')

super().__setattr__(name, value) # 使用 super() 委托给父类

class LocalState(State):

def __init__(self):

super().__init__()

self.logger = logger

self.ll = 2

if __name__ == '__main__':

state = LocalState()

state.ll = 22222

print(state.ll)

from loguru import logger

class State:

def __setattr__(self, name, value):

if hasattr(self, 'logger'):

self.logger.info(f'wwwwasdasd')

super().__setattr__(name, value) # 使用 super() 委托给父类

class LocalState(State):

def __init__(self):

super().__init__()

self.logger = logger

self.ll = 2

if __name__ == '__main__':

state = LocalState()

state.ll = 22222

print(state.ll)


回答:

python">import abc

from loguru import logger

class State:

def __init__(self):

pass

@property

@abc.abstractmethod

def get_logger(self):

raise "子类实现该方法"

def __setattr__(self, name, value):

self.get_logger.info(f"wwwwasdasd") # 问题代码

self.__dict__[name] = value

class LocalState(State):

def __init__(self):

super().__init__()

self.ll = 2

@property

def get_logger(self):

# 可以返回任意一个logger,父类调用该方法取决于子类的实现

return logger

if __name__ == "__main__":

state = LocalState()

state.ll = 22222

print(state.ll)

以上是 python 父子属性访问? 的全部内容, 来源链接: utcz.com/p/938858.html

回到顶部