【发布时间】:2014-06-14 19:53:31
【问题描述】:
我不明白的是b = Bar(a)。它有什么作用? Bar 如何将a 作为参数?
这不是说Bar 继承自a 吗? Bar.Foo1 = Foo 是什么?这是否意味着Foo1 是类Foo() 的一个实例?当 Foo1 本身是一个对象时,我们如何访问它? b.arg.variable 是什么意思?这不是说b 有一个方法arg,它有一个名为variable 的变量吗?以下代码来自this 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
【问题讨论】:
-
您应该阅读 the Python tutorial 以熟悉 Python 的基础知识。
-
我读到了。没有将对象传递给另一个类这样的事情。而且我无法从其他来源获得
-
它被描述为here。 Python 中的一切都是对象。将对象传递给类与传递整数(如该示例)、字符串或其他任何东西没有什么不同。
-
那么b是Bar类的一个对象,会调用其构造函数来初始化b,a`s(Foo())还是Bar()?什么是 b.arg.variable?
-
我不明白你在问什么。
a已经用a = Foo()行创建,当时调用了Foo 的__init__。当Bar(a)被执行时,就会调用Bar的__init__。您发布的示例中的 cmets 似乎已经大部分回答了您提出的问题。