我不明白的是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 = " Bar is now Baz" #
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) #
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