【问题标题】:Instantiating a class by passing self as argument通过传递 self 作为参数来实例化一个类
【发布时间】:2021-12-29 12:10:54
【问题描述】:

我遇到了一些 python 示例,其中通过调用类并将“self”传递给它来创建类实例。我似乎无法理解它的含义以及我们何时会使用这种结构。

下面是一个示例摘录,其中一个类在另一个类中实例化。我“认为”我也看到过类似objA = Class_def(self) 的东西。我不记得我在哪里看到的,所以最好知道它是否可能。

class BaseState(object):

    def __init__(self, protocol):
        self.protocol = protocol
    
    def connect(self, request):
        state = self.__class__.__name__



class IdleState(BaseState):

    def connect(self, request):
        return self.protocol.doConnect(request)



class ConnectingState(BaseState):

    def handleCONNACK(self, response):
        self.protocol.handleCONNACK(response)



class ConnectedState(BaseState):


    def disconnect(self, request):
        self.protocol.doDisconnect(request)


class BaseProtocol(Protocol):

    def __init__(self, factory):

    ###    
    # what is happening here -
    ###

        self.IDLE        = IdleState(self)
        self.CONNECTING  = ConnectingState(self)
        self.CONNECTED   = ConnectedState(self)
        self.state       = self.IDLE

【问题讨论】:

  • self in class 指的是类对象。假设一个类有一个名为 name 的变量,self.name = something。而当我们创建该对象的一个​​实例时,假设它是 Xself.name 将在定位对象 X 时变为 X.name。你可以阅读更多关于它link here
  • 您好,感谢您的评论。但这不是我的问题,我问的是self.IDLE = IdleState(self)这条线是做什么的?
  • 在您的示例中,self.IDLE 将从名为 IdleState 的方法中获取其值,同时将对象本身作为该方法的参数传递
  • 创建类的实例时一般不会显式传递self。然而,该类的所有方法都将通过通常给定该名称的参数将当前实例传递给它们。

标签: python oop


【解决方案1】:

一般来说,类总是作为参数传递给它的方法,这就是它们的工作方式。虽然在例如C++ 是隐式的,Python 是显式的。

在 BaseProtocol 中,您正在初始化 BaseProtocol 类的成员。初始化时,self 是多余的,因为 IdleState 方法的构造函数不需要访问它的实例变量,所以你可以删除它。但是,如果您对成员 IDLE 执行某些操作,例如调用使用其实例变量的方法,则需要传递 self

了解更多: https://www.knowledgehut.com/blog/programming/self-variabe-python-examples

【讨论】:

    【解决方案2】:

    绝对可以这样做,因为self 是python 传递的默认对象-

    class a:
      def __init__(self,__self,x):
        self.x=x
        print(self.x) #the local x that is passed into the object
        print(__self.x) #the x that is in the self that is passed into the object
    
    class b:
      def __init__(self,x):
        self.x=x
        obj=a(self,'foo')
    
    obj=b('baz') #should print 'foo', then 'baz'
    

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 2013-06-23
      • 1970-01-01
      相关资源
      最近更新 更多