英文:
How to use condition to check a child-class inside a parent-class method, if the child-class is in other py script?
问题
我有一个在parent.py中的父类
class Parent:
def __init__(self):
pass
def some_function(self):
if self.__class__ is Child_One:
pass # 做一些事情
elif self.__class__ is Child_Two:
pass # 做其他事情
然后我有另外两个child_one.py和child_two.py,它们包含类似的代码:
from .parent import Parent
class Child_One(Parent):
def child_function(self):
self.some_function()
在我将Child_One
和Child_Two
从parent.py中分离出来之前,这个函数运行正常。但是自从我将这两个子类移到其他脚本中以便更好地维护代码之后,这两个条件会比较一个未定义的对象,这是无效的。
有没有办法可以修复这个问题?
英文:
I have a parent class in a parent.py
class Parent:
def __init__(self):
pass
def some_function(self):
if self.__class__ is Child_One:
pass # do something
elif self.__class__ is Child_Two:
pass # do other things
Then I have another child_one.py and child_two.py which contains similar codes:
from .parent import Parent
class Child_One(Parent):
def child_function(self):
self.some_function()
Before I separated Child_One
and Child_Two
from parent.py, the function works fine. But since I moved the two-child classes into other scripts for better code maintenance, the two conditions would be comparing an undefined object, which is invalid.
Is there any way I can fix this?
答案1
得分: 1
以下是您要翻译的部分:
真正的问题在于您的父类依赖于它自己的子类。这是一个重大的设计问题 - 父类不应该知道任何关于其子类的信息(至少不应该有硬编码的信息)。而且,您存在这种依赖关系的原因(进行与类型相关的行为的类型检查)是另一个设计缺陷 - 面向对象的基本原则是通过多态分发(通常是方法调用)来取代这些依赖关系。
换句话说,您想在基类中实现一个存根 "do something":
class Parent(object):
def do_something_special(self):
pass
然后在子类中实现它(从Parent.some_function
中移动相关代码):
class ChildOne(Parent):
def do_something_special(self):
# do something
class ChildTwo(Parent):
def do_something_special(self):
# do something else
最后重构Parent.some_function()
:
def some_function(self):
# 这将调用适当的子类实现
self.do_something_special()
英文:
Wile there are indeed technical ways to do exactly what you ask for, those are actually the wrong solutions to the wrong problem.
The real problem here is that your parent class is depending on it's own child classes. This is a major design issue - a parent class should not know anything about its children (nothing hard-coded at least). Also, the reason you have this dependency (doing typechecking for type-dependent behaviour) is another design flaw - the very basis of OO is to replace those by polymorphic dispatch (most often method calls).
IOW, you want to implement a stub "do something" in your base class:
class Parent(object):
def do_something_special(self):
pass
Then implement it in your child classes (moving the relevant code from Parent.some_function
):
class ChildOne(Parent):
def do_something_special(self):
# do something
class ChildTwo(Parent):
def do_something_special(self):
# do something else
and finally refactor Parent.some_function()
:
def some_function(self):
# this will invoke the proper subclass implementation
self.do_something_special()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论