将类的实例(类的对象)传递给python中的另一个类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24223722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:15:27  来源:igfitidea点击:

Passing an instance of a class(object of a class) to another class in python

pythonoopparameter-passing

提问by qurius

What I do not understand is b = Bar(a). What does it do? How is Bar taking a as an argument? Wont that mean Bar inherit from a? What is Bar.Foo1 = Foo? Does it means Foo1 is an instance of class Foo()? How do we access Foo1 when it itself is an object? What is the meaning of b.arg.variable? Doesn`t it means b has a method arg which has a variable called variable? The following code is from the answer

我不明白的是b = Bar(a)。它有什么作用?Bar 如何将 a 作为参数?这是否意味着 Bar 继承自 a?什么是 Bar.Foo1 = Foo?这是否意味着 Foo1 是类 Foo() 的实例?当 Foo1 本身是一个对象时,我们如何访问它?b.arg.variable 是什么意思?这不是意味着 b 有一个方法 arg 有一个名为 variable 的变量吗?以下代码来自 答案

Forgive me if the question is naive. I just could not find parsing objects as an argument to another class. Any clarification would be great!

如果问题很幼稚,请原谅我。我只是找不到解析对象作为另一个类的参数。任何澄清都会很棒!

  class Foo (object):
  #^class name  #^ inherits from object

      bar = "Bar" #Class attribute.

      def __init__(self):
          #        #^ The first variable is the class instance in methods.  
          #        #  This is called "self" by convention, but could be any name you want.


          self.variable="Foo" #instance attribute.
          print self.variable, self.bar  #<---self.bar references class attribute
          self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
          print self.variable, self.bar  

       def method(self,arg1,arg2):
          #This method has arguments. You would call it like this : instance.method(1,2)
          print "in method (args):",arg1,arg2
          print "in method (attributes):", self.variable, self.bar


 a=Foo() # this calls __init__ (indirectly), output:
             # Foo bar
             # Foo  Bar is now Baz
 print a.variable # Foo
 a.variable="bar"
 a.method(1,2) # output:
               # in method (args): 1 2
               # in method (attributes): bar Bar is now Baz
 Foo.method(a,1,2) #<--- Same as a.method(1,2).  This makes it a little more explicit what the argument "self" actually is.

 class Bar(object):
     def __init__(self,arg):
          self.arg=arg
          self.Foo1=Foo()

 b=Bar(a)
 b.arg.variable="something"
 print a.variable # something
 print b.Foo1.variable # Foo

回答by BrenBarn

Here is a simpler example. Suppose you have these classes:

这是一个更简单的例子。假设你有这些类:

class Foo(object):
    pass

class Bar(object):
    def __init__(self, arg):
        self.arg = arg

Here are two things you could do:

您可以执行以下两项操作:

# Option 1: pass in an integer
>>> b = Bar(1)
>>> b.arg
1

# Option 2: pass in a Foo object
>>> a = Foo()
>>> b = Bar(a)
>>> b.arg
<__main__.Foo object at 0x0000000002A440F0>

There is no differencein how the two cases are handled. Passing in a(a Foo object) is no different from passing in an integer. All that Bardoes is store the value that is passed in, and it can store it just the same whether it is a Foo or an int. When you call Bar(something), it is entirely up to the Barclass how to handle the object that is passed in. The type of the passed-in object is not involved except insofar as Barchooses to explicitly involve it (e.g., by calling methods on the passed in object).

这两种情况的处理方式没有区别。顺便a(Foo对象)是从传入的整数没有什么不同。所有这一切Bar确实是存储在传递的价值,它可以存储它一样的无论是富或int。当您调用 时Bar(something),完全取决于Bar类如何处理传入的对象。不涉及传入对象的类型,除非Bar选择显式涉及它(例如,通过调用传入对象的方法)目的)。

回答by Linguist

"What I do not understand is b = Bar(a). What does it do?"

“我不明白的是 b = Bar(a)。它有什么作用?”

b = Bar(a)does two things. First, it creates an object of class Bar(with any class variables and methods attached). Then, it runs __init__with the first argument (self) pointing to the object that was just created, and with aas the second argument (arg). While running __init__, as one of the commands in that method, it sets self.argto point to the object pointed to by arg(i.e. to the object pointed to by the variable a). Finally, the variable bis set to refer to the object that was created.

b = Bar(a)做两件事。首先,它创建一个类的对象Bar(附加了任何类变量和方法)。然后,它运行__init__时第一个参数 ( self) 指向刚刚创建的对象,a第二个参数 ( arg)作为第二个参数运行。在运行时__init__,作为该方法中的命令之一,它设置self.arg为指向所指向的对象arg(即指向变量所指向的对象a)。最后,变量b被设置为引用创建的对象。

It may help to think this way: a variable in Python is really just a pointer that points to an object. You can have more than one variable pointing to the same object. In this case, aand b.argboth point to the same object.

以这种方式思考可能会有所帮助:Python 中的变量实际上只是一个指向对象的指针。可以有多个变量指向同一个对象。在这种情况下,a并且b.arg都指向同一个对象。

I found this sort of thing confusing too, at first. I had seen the advice to think of variables as separate concepts from the object they point to and ignored it as unnecessarily complicating things, but I had to go back to accepting that way of thinking in order to make sense of things. People do often use the variable as a name to refer to the object it points to; you just have to know when to take this literally or not.

起初,我也发现这种事情令人困惑。我已经看到了将变量视为与其指向的对象分开的概念的建议,并将其忽略为不必要的复杂事物,但我不得不重新接受这种思维方式以理解事物。人们确实经常使用变量作为名称来引用它所指向的对象;你只需要知道什么时候从字面上理解这个。

"Wont that mean Bar inherit from a?"

“这是否意味着 Bar 继承自 a?”

No. If ais a class, then class Bar(a)would mean that Bar inherits from a. But in b = Bar(a), ais an object being passed as an argument to __init__.

不。如果a是一个类,那么class Bar(a)就意味着 Bar 继承自a. 但是在 b = Bar(a),a是一个对象作为参数传递给__init__

"What is Bar.Foo1 = Foo?"

“什么是 Bar.Foo1 = Foo?”

Sorry -- I don't see that in the example code you gave.

抱歉 - 我在您提供的示例代码中没有看到。

"What is the meaning of b.arg.variable?"

“b.arg.variable 是什么意思?”

bis an object (i mean, brefers to an object) and b.argis one of the attributes of that object. Methods and variables are different types of attributes. In this case, b.argis a variable pointing to an object. The object referred to by b.arghas attribute variable, which is a variable.

b是一个对象(我的意思b是指一个对象)并且b.arg是该对象的属性之一。方法和变量是不同类型的属性。在这种情况下,b.arg是指向对象的变量。引用的对象b.arg具有属性variable,它是一个变量。

b.argrefers to the same object that arefers to, therefore b.arg.variableis the same variable as a.variable. It not only points to the same object, but actually is the same variable. The object it points to is the string "something".

b.arg指代所指的同一个对象a,因此与b.arg.variable是同一个变量a.variable。它不仅指向同一个对象,而且实际上是同一个变量。它指向的对象是字符串"something"

@Brenbarn: I think that's what quirius meant by "Wont that mean Bar inherit from a?".

@Brenbarn:我认为这就是 quirius 的意思“这是否意味着 Bar 继承自 a?”。