我不明白的是b = Bar(a)。它有什么作用? Bar如何将a作为参数?这是否意味着Bar从a继承?什么是Bar.Foo1 = Foo?这是否意味着Foo1是Foo()类的实例?当Foo1本身是一个对象时,我们如何访问它? b.arg.variable是什么意思?这不是说b有一个arg方法,其中有一个称为变量的变量吗?以下代码来自answer
如果问题很幼稚,请原谅我。我只是找不到解析对象作为另一个类的参数。任何澄清都很好!
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
“我不明白的是b = Bar(a)。它有什么作用?”
b = Bar(a)
做两件事。首先,它创建一个类Bar
的对象(附带任何类变量和方法)。然后,它以第一个参数(__init__
)指向刚创建的对象,并以self
作为第二个参数(a
)运行arg
。运行__init__
时,作为该方法中的命令之一,它将self.arg
设置为指向arg
指向的对象(即,指向变量a
指向的对象)。最后,将变量b
设置为引用已创建的对象。
这可能有助于这样思考:Python中的变量实际上只是指向对象的指针。您可以有多个变量指向同一个对象。在这种情况下,a
和b.arg
都指向同一对象。
起初,我也发现这种事情令人困惑。我已经看到了将变量视为与它们所指向的对象不同的概念的建议,而忽略了变量不必要地使事情变得复杂,但是我不得不回到接受这种思维方式的角度来理解事物。人们经常使用变量作为名称来引用它指向的对象。您只需要知道什么时候该进行字面翻译即可。
“这是否意味着Bar继承自a?”
没有如果a
是一个类,则class Bar(a)
表示Bar继承自a
。但在b = Bar(a)
,a
是作为参数传递给__init__
的对象。
“ Bar.Foo1 = Foo是什么?”
对不起,您提供的示例代码中没有显示。
“ b.arg.variable是什么意思?”
b
是一个对象(我是说,b
是一个对象),b.arg
是该对象的属性之一。方法和变量是不同类型的属性。在这种情况下,b.arg
是指向对象的变量。 b.arg
引用的对象具有属性variable
,它是一个变量。
b.arg
表示与a
相同的对象,因此b.arg.variable
与a.variable
相同。它不仅指向相同的对象,而且实际上是相同的变量。它指向的对象是字符串"something"
。
@@ Brenbarn:我认为这是quirius的意思,“难道Bar将从a继承吗?”。
这里是一个简单的例子。假设您具有以下类:
class Foo(object):
pass
class Bar(object):
def __init__(self, arg):
self.arg = arg
您可以做两件事:
# 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>
这两种情况的处理方式没有差异]。传入a
(一个Foo对象)与传入整数没有什么不同。 Bar
所做的只是存储传入的值,无论是Foo还是int,它都可以存储相同的值。调用Bar(something)
时,如何处理传入的对象完全取决于Bar
类。除非Bar
选择显式包含它,否则不涉及传入对象的类型。例如,通过对传入的对象调用方法)。