- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我发现自己为预定义的对象编写了许多小的子类。但是,我创建的每个子类都包含大量重复代码(用于基类实例化)。本质上,我使用子类来存储默认的初始化属性,特定于子类,并为基类所共有。
使用许多只有 init() 的小子类是否可以接受?
例如:我创建了一个包含基类和子类的模块(我有 30 个子类,参数和默认参数略有不同)。
#animals.py
#Contains animal definitions and methods
class Animal(object):
def __init__(self, name, weight, cute=False, kind=None, image=None):
#Instantiation attributes
self.name = name
self.weight = weight
self.cute = cute
self.kind = kind
self.image = image
#Attributes common to all animals
self.extinct = False
def get_animal_stats(self):
print arbitrary_animal_stat
class Dog(Animal):
def __init__(self, name, weight, kind="Mixed Breed"):
Animal.__init__(self, name, weight, cute=True, kind=kind, image="dog.com")
class Cat(Animal):
def __init__(self, name, weight):
Animal.__init__(self, name, weight, cute=True, image="cat.com")
并通过通用 Animal 类或更具体、预定义的 Animal 子类在其他模块中创建实例(tab 完成是必不可少的,因此我可以引用特定的动物子类)。
import animals #Uses animal definitions from animals.py
my_animals = [
animals.Animal("Python", 2.7, cute=False),
animals.Dog("Snoopy", 60, kind="Cartoon"),
animals.Cat("Tigger", 50, kind="Tiger"),]
for animal in my_animals:
animal.get_animal_stats()
我曾尝试使用变量来替换子类定义。如果我想修改任何东西,这会很麻烦,因为我必须记住默认值和它们的顺序,而且看起来不如子类化那么明确。
#Use of variables instead of subclasses
dog = ("True", "Mixed Breed", "dog.com")
Animal("default dog", 60, *animals.dog)
Animal("special dog", 60, cute=False, kind="Guard Dog", image=animals.dog[2])
字典几乎和等效的子类一样麻烦,因为它们的定义中有很多重复代码,而且它看起来不如更健壮的子类对应物那么明确。
#Use of dictionaries instead of subclasses
dog = {"cute": True, "kind": "Mixed Breed", "image": "dog.com"}
Animal("default dog", 60, **animals.dog)
Animal("special dog", 60, cute=False, kind="Guard Dog", image=animals.dog["image"])
我应该重新考虑在这种情况下使用子类吗?如果是这样,实现此目的的 Pythonic 方法是什么?
我应该考虑@classmethod 还是@staticmethod?我理解他们在理论上做了什么,但不知道如何/何时实现它们。
谢谢大家的回答。在回复之前我已经多次阅读它们,并提出了稍微修改过的例子来澄清我仍然难以理解的概念。我是 StackOverflow 的新手并以这种方式回复,以便我可以详细说明。如果这是对“编辑”的不当使用,请告诉我如何继续。
-我认为您认为在这种情况下可以接受子类化?
-我喜欢你的类变量技术。我计划实现它。
-我认为您对 **kwargs 的使用很有希望,但没有引用源 animals.py',当我初始化子类时,您如何知道哪些键值对在父类中有效?在实例化子类时,它们在上下文中不可用。
-我考虑过为每个子类定义一组默认的 **kwargs,类似于您的类变量技术。但是,我不完全理解如果我越过键值然后输入 **kwargs(在 **kwargs 中定义了相同的键)会发生什么。
class Dog(Animal):
WOOF, YAP, HUSH = 'woof', 'yap', 'hush_puppy'
kwargs = {cute: True, kind: "Generic", image_path: "dog.com"}
def __init__(self, name, weight, bark=WOOF, **kwargs):
self.bark = bark
super(Dog, self).__init__(name, weight, **kwargs)
dog1 = Dog("Snoopy", 60, **Dog.kwargs)
dog2 = Dog("Otis", 30, bark=Dog.YAP, cute=False, **Dog.kwargs)
这是有效的语法吗? Dog.kwargs 中的 cute=True 会超过我在实例化中设置 cute=False 吗?
关于分类学的有趣观点。幸运的是,我确实有有限数量的子类(我不需要一直特化),并且对于我的使用来说,通过 Animal 基类创建 Dog 不是 type(Dog) 是可以接受的。
考虑到这一点,还有其他需要考虑的概念吗?
最佳答案
我会使用 super 和 **kwargs 并添加任何仅与该子类相关的特定属性。
class Dog(Animal):
WOOF, YAP, HUSH = 'woof', 'yap', 'hush_puppy'
def __init__(self, name, weight, bark=WOOF, **kwargs):
self.bark = bark
super(Dog, self).__init__(name, weight, **kwargs)
class Cat(Animal):
HAIR_LONG, HAIR_SHORT = 'long', 'short'
def __init__(self, name, weight,hair=HAIR_LONG, **kwargs):
self.hair = hair
super(Cat, self).__init__(name, weight, **kwargs)
dog = Dog("Snoopy", 60, bark=Dog.HUSH)
cat = Cat("Tigger", 50, kind="Tiger",hair=Cat.HAIR_SHORT)
关于减少基类中小子类数量的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26557364/
经过几个小时的(重新)搜索,我无法想出普通抽象类和使用模板模式之间的可解释区别。 我唯一看到的是: 使用抽象类时,您需要实现所有方法。但是在使用模板方法时,您只需要实现这两个抽象方法。 有人可以向我解
我正在尝试实现一种算法,该算法可找到以下形状给出的外多边形的每个单独边的对应区域。也就是说,1,2 边的相应区域是 [1,6,7,8,2],2,3 边的区域是 [2,8,3] 等等,CCW 或 CW
我正在尝试在派生 self 的 BaseController 类的任何 Controller 上自动设置一个属性。这是我的 Application_Start 方法中的代码。 UnitOfWork 属
我正在使用 mgcv 包通过以下方式将一些多项式样条拟合到一些数据: x.gam smooth$knots [1] -0.081161 -0.054107 -0.027053 0.000001
考虑以下代码: void foo(){ ..... } int main() { int arr[3][3] ; char string[10]; foo();
本书The c++ programming language有这个代码: class BB_ival_slider : public Ival_slider, protected BBslider {
是否有一个 package.json 属性可用于指定模块解析应启动的根文件夹? 例如,假设我们在 node_modules/mypackage/src/file1 中有一个安装。我们要导入的所有文件都
我正在尝试使用聚合函数来实现与 SQL 查询相同的结果: 查询语句: sqldf(" SELECT PhotoID, UserID,
我正在比较使用 LOESS 回归的两条线。我想清楚地显示两条线的置信区间,我遇到了一些困难。 我尝试过使用各种线型和颜色,但在我看来,结果仍然是忙碌和凌乱。我认为置信区间之间的阴影可能会使事情变得更清
给定这段代码 public override void Serialize(BaseContentObject obj) { string file = ObjectDataStoreFold
我正在构建某种工厂方法,它按以下方式将 DerivedClass 作为 BaseClass 返回: BaseClass Factory() { return DerivedClass(); }
当重写 class delegation 实现的接口(interface)方法时,是否可以调用通常从重写函数中委托(delegate)给的类?类似于使用继承时调用 super 的方式。 来自docum
我有一个基类 fragment (如下所示)。我在其他 3 个 fragment 类中扩展了此类,每个类都共享需要在这 3 个 fragment 中访问的相同 EditText。因此,我在基类中设置了
如何在不加载额外库的情况下在 R 中计算两个排列之间的 Kendall tau 距离(又名冒泡排序距离)? 最佳答案 这是一个 O(n.log(n)) 的实现,在阅读后拼凑而成,但我怀疑可能有更好的
情况 我创建了一个具有国际化 (i18n) 的 Angular 应用程序。我想在子域中托管不同的版本,例如: zh.myexample.com es.myexample.com 问题 当我使用命令 n
std::is_base_of 之间的唯一区别和 std::is_convertible是前者在 Base 时也成立是 私有(private)或 protected Derived 的基类.但是,您何
我创建了一个名为 baseviewcontroller 的父类(super class) uiviewcontroller 类,用于包含大多数应用屏幕所需的基本 UI。它包括一个自定义导航栏和一个“自
我是一名优秀的程序员,十分优秀!