![](/img/trans.png)
[英]How to implement abstract class methods as static method in inherited class in python?
[英]How to implement python class attribute containing methods?
我有一個Animal類,並且我希望它具有一個允許訪問特定功能集的屬性。
class Animal(object):
def __init__(self, age):
self.age = age
rex = Animal()
rex.actions.bark()
rex.actions.say_age()
我嘗試創建一個Actions類並將其用作具有多重繼承的mixin,但這只允許我執行以下操作:
rex.say_age()
這不是我想要的。
我還嘗試創建一個充滿靜態方法的Actions類並使用它們,但這迫使我將Animal的屬性傳遞給方法。
我知道pandas實現了這一點(Series.str是一個示例),但看起來它需要大量專有開銷
有pythonic的方法可以做到這一點嗎?
只需創建另一個將Animal
構造函數的類即可。
class AnimalActions(object):
def __init__(self, animal):
self.animal = animal
class Animal(object):
def __init__(self, age):
self.age = age
self.actions = AnimalActions(self)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.