如何在python中创建一个继承另一个类的方法的类,但是只更改某个方法的某些部分?

时间:2022-09-11 20:55:10

example: I have a class that is called "MicroSDCard" this class inherits from a class that is called "MemoryCard", but there is one change between them. MicroSDCard can get another value that is called Frequency, and should retrurn it using the init method like this "self.max_freq". How can I make it happen? Thank you in advance

示例:我有一个名为“MicroSDCard”的类,这个类继承自一个名为“MemoryCard”的类,但它们之间有一个变化。 MicroSDCard可以获得另一个名为Frequency的值,并且应该使用init方法重新启动它,例如“self.max_freq”。我怎样才能实现呢?先感谢您

2 个解决方案

#1


0  

An example:

class MemoryCard(object):
    def __init__(self, size):
        print ('MemoryCard size is ', size)

class MicroSDCard(MemoryCard):
    def __init__(self, max_freq, *args, **kw):
        MemoryCard.__init__(self, *args, **kw)
        self.max_freq = max_freq


print ("MicroSDCard max_freq is ", MicroSDCard(5, size=3).max_freq)

#2


0  

Maybe I didn't understand you correctly, but I would do the following:

也许我没有正确理解你,但我会做以下事情:

  1. re-write the __init__ method in MicroSDCard class with the new attribute.
  2. 使用new属性重写MicroSDCard类中的__init__方法。

  3. for any method that utilize this new attribute, you need to re-write (overload) it in the MicroSDCard class definition.
  4. 对于使用此新属性的任何方法,您需要在MicroSDCard类定义中重写(重载)它。

That looks too simple, so I guess I didn't get your question :)

这看起来太简单了,所以我想我没有得到你的问题:)

#1


0  

An example:

class MemoryCard(object):
    def __init__(self, size):
        print ('MemoryCard size is ', size)

class MicroSDCard(MemoryCard):
    def __init__(self, max_freq, *args, **kw):
        MemoryCard.__init__(self, *args, **kw)
        self.max_freq = max_freq


print ("MicroSDCard max_freq is ", MicroSDCard(5, size=3).max_freq)

#2


0  

Maybe I didn't understand you correctly, but I would do the following:

也许我没有正确理解你,但我会做以下事情:

  1. re-write the __init__ method in MicroSDCard class with the new attribute.
  2. 使用new属性重写MicroSDCard类中的__init__方法。

  3. for any method that utilize this new attribute, you need to re-write (overload) it in the MicroSDCard class definition.
  4. 对于使用此新属性的任何方法,您需要在MicroSDCard类定义中重写(重载)它。

That looks too simple, so I guess I didn't get your question :)

这看起来太简单了,所以我想我没有得到你的问题:)