我不明白的是b = Bar(a)
。它有什么作用?怎么Bar
taking a
作为一个论点?
那岂不是意味着Bar
继承自a
?什么是Bar.Foo1 = Foo
?是不是意味着Foo1
是类的一个实例Foo()
?我们如何访问Foo1
当它本身是一个对象时?是什么意思b.arg.variable
?是不是意味着b
有一个方法arg
其中有一个名为variable
?以下代码来自这个答案 https://stackoverflow.com/a/11421962/3519372
我只是找不到解析对象作为另一个类的参数。
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
and b.arg
两者都指向同一个对象。
起初我也发现这种事情很令人困惑。我曾看到过将变量视为与它们所指向的对象不同的概念的建议,并忽略了它,因为它使事情不必要地复杂化,但我必须重新接受这种思维方式才能理解事物。人们确实经常使用变量作为名称来引用它所指向的对象;你只需要知道什么时候该从字面上理解这一点。
“这是否意味着Bar继承了a?”
No. If 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 吗?”的意思。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)