理解Python类和基类

2024-04-19 19:19:13 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有一个实例

client = PiHttpClient("192.168.1.234")
# RPi native GPIO
gpio = NativeGPIO(client)
gpio.setFunction(25, "out")
state = True

从客户端.py我有密码

class PiMixedClient():
    def __init__(self, host, port=8000, coap=5683):
    def sendRequest(self, method, uri):

class PiHttpClient(PiMixedClient):
    def __init__(self, host, port=8000):
        PiMixedClient.__init__(self, host, port, -1)
class NativeGPIO(GPIO):
    def __init__(self, client):
        RESTAPI.__init__(self, client, "/GPIO")

class GPIO(Device):
    def __init__(self, client, name):
        Device.__init__(self, client, name, "digital")

    def getFunction(self, channel):
        return self.sendRequest("GET", "/%d/function" % channel)

    def setFunction(self, channel, func):
        return self.sendRequest("POST", "/%d/function/%s" % (channel, func))

class Device(RESTAPI):
    def __init__(self, client, name, category):
        RESTAPI.__init__(self, client, "/devices/" + name + "/" + category)

class RESTAPI():
    def __init__(self, client, path):
        self.client = client
        self.path = path

    def sendRequest(self, method, path):
        return self.client.sendRequest(method, self.path + path)
  1. 那么,从上面看,当它执行PiHttpClient(“192.168.1.234”)时,主机=“192.168.1.234”,对吗?但是初始化(self,host,port=8000)查找self,host。我不认为自我会被当作论据。

  2. 那么在PiMixedClient内部,由于PiHttpClient扩展了PiMixedClient,那么它的主机和自身应该与PiMixedClient相同

  3. 然后gpio=NativeGPIO(client)再次进入NativeGPIO的init(self,client),从调用函数我不需要提供self?

  4. 所以当扩展到最低级别时,它就变成了RESTAPI基类,它的sendRequest方法是来自client的,而client是来自PiMixedClient类的sendRequest?


Tags: pathnameselfclientrestapihostgpioinit
1条回答
网友
1楼 · 发布于 2024-04-19 19:19:13
  1. 是的-python方法总是以self作为第一个参数,您可能想看看类上的docs。你知道吗
  2. 是的
  3. -你知道吗
  4. 不需要。如果创建类的实例,则不需要手动suply self(如果要重写init方法,则需要手动suply self)
  5. 是的

但实际上,看看python文档,它们相当不错。你知道吗

相关问题 更多 >