11 python class parent instance
如何在此代码示例中从"child"访问"myvar":
class Parent():
def __init__(self):
self.myvar = 1
class Child(Parent):
def __init__(self):
Parent.__init__(self)
# this won't work
Parent.myvar
child = Child()
Run Code Online (Sandbox Code Playgroud)
小智 14
Parent是一个类 - 蓝色打印而不是它的实例,在OOPS中访问它需要的实例的对象的属性,这里self/child是实例,而Parent/Child是类...
看到下面的答案,可能会澄清你的疑虑.
class Parent():
def __init__(self):
self.myvar = 1
class Child(Parent):
def __init__(self):
Parent.__init__(self)
# here you can access myvar like below.
print self.myvar
child = Child()
print child.myvar
Run Code Online (Sandbox Code Playgroud)
Bil*_*lis 10
当前的答案来自继承的角度,但这并不总是您想要的 - 有时您可能希望子对象是与父对象完全不同类型的对象,但仍然可以访问父属性。
对于业务类比,请考虑具有 Worksheet 子项的 Excel 工作簿,其本身也具有 Range 子项,等等。
另一种方法(不是唯一的方法)是将父级作为参数传递给子级,以创建与父级相对应的属性:
class Parent(object):
def __init__(self, parent_value):
self.parent_value = parent_value
self.child = Child(self)
class Child(object):
def __init__(self, _parent):
self.parent = _parent
self.child_value = 0
new_parent = Parent(1)
print(new_parent.parent_value) # prints 1
new_child = new_parent.child
print(new_child.child_value) # prints 0
print(new_child.parent.parent_value) # prints 1
new_parent.parent_value = 100
print(new_child.parent.parent_value) # prints 100
Run Code Online (Sandbox Code Playgroud)
请注意,这与实例化child的同时new_parent实例化。要访问父级的属性,只需遍历parent属性即可。
您可以扩展它,以便可以Child通过该new_parent对象创建该类的多个实例。下面的代码是执行此操作的一种简单方法,它将child属性替换为children属性和add_child方法。
class Parent(object):
def __init__(self, parent_value):
self.parent_value = parent_value
self.children = []
def add_child(self, child_value):
new_child = Child(child_value, _parent=self)
self.children.append(new_child)
return new_child # allows add_child to assign a variable
class Child(object):
def __init__(self, child_value, _parent):
self.parent = _parent
self.child_value = child_value
new_parent = Parent(1)
# add 3 Child instances with child_values 2, 4, 8
[new_parent.add_child(v) for v in [2, 4, 8]]
# add another child that utilises the return statement
extra_child = new_parent.add_child(16)
for child in new_parent.children:
print(child.child_value) # prints 2, 4, 8, 16
print(child.parent.parent_value) # prints 1
new_parent.parent_value = 32
for child in new_parent.children:
print(child.parent.parent_value) # prints 32
# prove that extra_child is new_parent.children[3]
extra_child.child_value = 64
print(new_parent.children[3].child_value) # prints 64
Run Code Online (Sandbox Code Playgroud)