[英]Automatic inheritance of all base class attributes
I want to create a class that has two characteristics: 我想创建一个具有两个特征的类:
I want these two characteristics because I want to automatically inherit all the attributes and methods of the previous object (base class object) without having to do something like use the __init__
method since this will cause recalculation of the already computed initialization. 我想要这两个特征,是因为我想自动继承前一个对象(基类对象)的所有属性和方法,而不必执行__init__
方法之类的操作,因为这将导致重新计算已经计算的初始化。 And since there will be a lot of methods and attributes I don't think its good practice to do it manually. 而且由于会有很多方法和属性,所以我认为手动执行它不是一个好习惯。
My idea of the code would look something like this. 我对代码的想法看起来像这样。
class BaseClass(object):
def __init__(self, name, date):
self.name = name
self.date = date
def get_name_date(self):
self.name_date = self.name +self.date
class UpperClass(BaseClass):
def __init__(self):
self.date_name = self.date + self.name
I know the code above will not work and I dont want to do something like: 我知道上面的代码将不起作用,并且我不想做类似的事情:
class UpperClass(BaseClass):
def __init__(self):
super(BaseClass, self).__init__(name, date)
self.date_name = self.date + self.name
Cause this will re-do calculations I already have. 因为这将重新执行我已经拥有的计算。 Maybe inheritance is not what I'm looking for, any pointers? 也许继承不是我想要的,任何指针?
Is this what you are looking for? 这是你想要的?
class BaseClass(object):
def __init__(self, name, date):
self.name = name
self.date = date
def get_name_date(self):
self.name_date = self.name +self.date
class UpperClass:
def __init__(self, baseobject):
self.baseobject = baseobject
self.date_name = baseobject.date + baseobject.name
def __getattr__(self, item):
return getattr(self.baseobject, item)
o1 = BaseClass('thmei', 'may')
o2 = UpperClass(o1)
print(o1.date) # may
print(o2.date) # may
print(o2.date_name) # maythmei
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.