1 import sys
2
3 class dummy(object):
4 def __init__(self, val):
5 self.val = val
6
7 class myobj(object):
8 def __init__(self, resources):
9 self._resources = resources
10
11 class ext(myobj):
12 def __init__(self, resources=[]):
13 #myobj.__init__(self, resources)
14 self._resources = resources
15
16 one = ext()
17 one._resources.append(1)
18 two = ext()
19
20 print one._resources
21 print two._resources
22
23 sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
这将打印的参考对象分配one._resources两个one和two对象.我认为这two将是一个空数组,因为如果在创建对象时没有定义它,它就会明确地设置它.取消注释也会myobj.__init__(self, resources)做同样的事情.使用super(ext, self).__init__(resources)也做同样的事情.
我可以使用它的唯一方法是使用以下方法:
two …Run Code Online (Sandbox Code Playgroud) 我正在编写这段代码作为面向对象编程的练习.
在这里,我试图将房屋定义为房间列表,并将每个房间定义为设备列表(例如灯具).
首先,我创建了所有对象,并将两个房间附加到房屋,并为每个房间添加了不同的设备.很基本的.
问题是,似乎设备被附加到两个房间.这是为什么?
代码:
#! /usr/bin/python
class House:
def __init__(self, rooms = list()):
self.rooms = rooms
print('house created')
class Room:
def __init__(self, name = 'a room', devs = list()):
self.name = name
self.devs = devs
print('room ' + self.name + ' created')
class Device:
def __init__(self, name = 'a device'):
self.name = name
print('device ' + self.name + ' created')
def main():
#1
h = House()
r1 = Room(name = 'R1')
r2 = Room(name = 'R2')
d1 = Device(name …Run Code Online (Sandbox Code Playgroud) 我想用一些可选参数定义一个函数,比如说A(强制性)和B(可选)。如果没有给定B,我希望它取与A相同的值。我该怎么做?
我已经尝试过了,但是不起作用(未定义名称“ B”):
def foo(A, B=A):
do_something()
Run Code Online (Sandbox Code Playgroud)
我知道参数的值未在函数主体之前分配。
假设我们有该函数f,并且我需要参数b默认为空列表,但由于可变默认参数的问题而无法设置 b=[]。
其中哪一个最Pythonic,或者有更好的方法吗?
def f(a, b=None):
if not b:
b = []
pass
def f(a, b=None):
b = b or []
pass
Run Code Online (Sandbox Code Playgroud) 为什么如下:
class A(object):
def __init__(self, var=[]):
self._var = var
print 'var = %s %s' % (var, id(var))
a1 = A()
a1._var.append('one')
a2 = A()
Run Code Online (Sandbox Code Playgroud)
造成:
var = [] 182897439952
var = ['one'] 182897439952
Run Code Online (Sandbox Code Playgroud)
我不明白为什么在使用可选关键字参数时它没有使用列表的新实例,有人能解释一下吗?