简体   繁体   English

在python中输入类型

[英]Type casting in python

I looked at similar question on SO but none of them answer my problem. 我在SO上看了类似的问题,但没有一个回答我的问题。 For Ex. 对于Ex。 How do you cast an instance to a derived class? 如何将实例强制转换为派生类? . But the answer doesn't seem to be what I want. 但答案似乎并不是我想要的。

Here is my situation. 这是我的情况。 I have a class structure like in Django 我有类似Django的类结构

class Base:
     ...some stuff...

class Derived(Base):
     ...some more stuff...

Now when I make some queries in Django, I always get objects of Base class. 现在,当我在Django中进行一些查询时,我总是得到Base类的对象。

 baseobj = get_object_or_404(Base, id = sid)

At runtime I can also encounter "Derived" objects which have some extra properties. 在运行时,我还可以遇到具有一些额外属性的“派生”对象。 I'm able to figure out if an object is Base or derived(there is sufficient info in Base class object). 我能够弄清楚一个对象是Base还是派生的(Base类对象中有足够的信息)。 But how should I access those extra fields which are present only in Derived class. 但是我应该如何访问仅在Derived类中出现的那些额外字段。 I'm not able to downcast "Base" -> "Derived". 我无法贬低“基地” - >“衍生”。 How should I handle it? 我应该怎么处理?

EDIT: 编辑:

I figured out the problem. 我解决了这个问题。 Django stores "additional properties" of Derived class in a separate table. Django在另一个表中存储Derived类的“附加属性”。 Hence problem arose due to this line of code. 因此,由于这行代码而出现了问题。

baseobj = get_object_or_404(Base, id = sid)

baseobj will always be of Base class and will not have any properties of Derived class. baseobj将始终为Base类,并且不具有Derived类的任何属性。 I have to make an additional query to get the Derived class object. 我必须进行额外的查询以获取Derived类对象。

baseobj = get_object_or_404(Base, id = sid)
if baseobj.isDerivedType:
      derivedobj = get_object_or_404(Derived, id = sid)

This sort of inheritance in Django-land smells like multi-table inheritance to me. Django-land 中的这种继承对我来说就像多表继承一样。 According to the doc, assuming everything is wired properly, you should be able to do: 根据文档,假设所有内容都正确连接,您应该能够:

baseobj.derived    # note: small 'd'

Normally, I would say that it's typical to use a try-except clause in a situation like this. 通常,我会说在这种情况下使用try-except子句是很典型的。

class thing1(object):
    def __init__(self):
        self.a = 5

class thing2(thing1):
    def __init__(self):
        super(thing2, self).__init__()
        self.b = 6

t = thing1()
try: 
    print(t.b)
except AttributeError: 
    print("handling the exception")

EDIT: But am I understanding your question correctly? 编辑:但我能正确理解你的问题吗? Answer: No. Oops! 答:没有。哎呀!

EDIT2: Nonetheless, it seems that some variation on the above try-except block would be better than accessing the database twice, as your edited question suggests. 编辑2:尽管如此,似乎上面的try-except块的某些变化比访问数据库两次更好,正如您编辑的问题所暗示的那样。

I have never had to do this in python. 我从来没有在python中这样做过。 It seems like a code smell that you have an instance of a type, and need to know the most derived type of the object. 看起来像代码气味,你有一个类型的实例,并需要知道对象的最派生类型。 You should already know what the type is based on the function that you're using. 您应该已经知道基于您正在使用的功能的类型。 Perhaps if you showed us the actual code that you are using, we'd be able to help you with a better solution. 也许如果您向我们展示了您正在使用的实际代码,我们将能够为您提供更好的解决方案。

The problem with checking if your object isDerivedType is that when you add another derived class, you will have to modify your base to do checks for the new derived type. 检查对象isDerivedTypeisDerivedType是,当您添加另一个派生类时,您必须修改基础以检查新的派生类型。 This breaks the model of object oriented programming. 这打破了面向对象编程的模型。 If someone else is using your code and they decide to derive from your class, they can't effectively do it. 如果其他人正在使用您的代码并且他们决定从您的课程中派生出来,那么他们就无法有效地执行此操作。

Try to work with the derived types as much as possible. 尝试尽可能使用派生类型。 The point of inheritance in Django is to allow code re-use and the sharing of data between classes - not information hiding. Django中的继承点是允许代码重用和类之间的数据共享 - 而不是信息隐藏。

Use the "lowercase" version of Derived class: 使用Derived类的“小写”版本:

class Base:
     base_attribute

class Derived(Base):
     derived_attribute

baseobj = get_object_or_404(Base, id = sid)
if baseobj.isDerivedType:
     print baseobj.derived.derived_attribute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM