简体   繁体   English

Python继承(OOP)

[英]Python inheritance (OOP)

I want create inheritor (descadent) of python's class time. 我想创建python上课时间的继承者(descadent)。 I use solving from next script, but I obtain message cannot create "builtin_function_or method" instance . 我使用下一个脚本中的解决方案,但获取消息无法创建“ builtin_function_or方法”实例 Where is problem,please? 请问哪里有问题?

from time import time as time
import _classA

class UserTime(time):
    def __init__(self):
        pass

time.time is a function not a class. time.time是一个函数而不是一个类。 You cannot inherit from a function. 您不能从函数继承。 In the module time struct_time is defined as a class. 在模块时间struct_time被定义为一个类。

from time import struct_time as time

class MyTime(time) :
    def __init__(self, time_as_sequence) :
        time.__init__(self, time_as_sequence)

        # Do what you like

Based on the Python docs for time.time , the time that you've imported there is a function, not a class, which is why you're getting that error message. 根据time.time的Python文档,导入的time是一个函数,而不是一个类,这就是为什么您收到该错误消息的原因。

datetime.time may be what you need instead. datetime.time可能是您需要的。

Actually what you're trying to do is ILLIGAL :) Anyway, you're trying to subclass a method of the class time which you can't do. 实际上,您尝试执行的操作是ILLIGAL :)无论如何,您都试图将无法执行的class time方法子类化。 Here's a little explanation why: 这是为什么的一些解释:

>>> import time
>>> type(time.time)
<class 'builtin_function_or_method'>
>>> type(time)
<class 'module'>

From what you can see above the time.time is a builtin function or method of a class (in this case, the class "time"), even if you cast a type on "time" itself, would result a class of type "module", which you cannot subclass aswell. 从上面的时间中可以看到,time.time是类的内置函数或方法(在这种情况下,类为“ time”),即使您将类型强制转换为“ time”本身,其结果也会是“模块”,您也不能将其子类化。 But, you could do something that i don't reccomend since it is useless (in my opinion): 但是,您可以做一些我不建议使用的操作,因为它没有用(我认为):

import time
class A(type(time)):
    pass

and it would magically be a class of type "type", which is what you want and answers to your question. 它将神奇地成为“类型”类型的类,这就是您想要的,并回答了您的问题。

>>> type(A)
<class 'type'>

But you have to deal with it in someway, so my question is, What are you actually trying to accomplish? 但是您必须以某种方式处理它,所以我的问题是,您实际上想完成什么? Do you really need to do sort of magic behind the scene to something that could be done in different ways (easily)? 您是否真的需要在幕后做一些魔术,可以用不同的方式(轻松地)完成某件事?

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

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